Reputation: 39
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")
Upvotes: 0
Views: 74
Reputation: 78994
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.
Upvotes: 3