0

These arrays contains same keys simple like follow topic (prop is unique): Check if associative array contains value, and retrieve key / position in array

<?php
$array = array(
array("prop" => "1", "content" => "text"),
array("prop" => "2", "content" => "text"),
array("prop" => "3", "content" => "text"),
array("prop" => "4", "content" => "text")
);
$found = current(array_filter($array, function($item) {
  return isset($item['prop']) && 3 == $item['prop'];
}));
print_r($found);

I got prop 3:

Array
(
  [prop] => 3
  [content] => text
)

So I want to replace value in $array with:

array("prop" => "3", "content" => "replaced text")
4
  • What? What result do you want? Commented Feb 20, 2018 at 21:57
  • array("prop" => "3", "content" => "replaced text") in $array Commented Feb 20, 2018 at 21:59
  • Is prop always unique? Commented Feb 20, 2018 at 22:02
  • yes always is unique Commented Feb 20, 2018 at 22:03

1 Answer 1

3

Since prop is unique, just extract the arrays using prop as the index and then access it that way:

$array = array_column($array, null, 'prop');
$array[3]['content'] = 'replaced text';

You might want to use an isset to make sure $array[3]['content'] exists.

Sign up to request clarification or add additional context in comments.

2 Comments

Technically shouldn't the OP access the value as $array['3']['content'], since "prop" is a string in the original array? I believe accessing it by an integer could cause issues between array position and array key name.
@Anthony: PHP creates integer keys from strings containing only integers var_dump(["1"=>"hello", "a"=>"hello"]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.