This question already has an answer here:
I have this kind of array:
Array
(
[0] => Array
(
[title] => Personal
[closeable] => 1
[visible] => 1
)
[1] => Array
(
[title] => My contracts
[closeable] => 1
[visible] => 1
)
[2] => Array
(
[title] => Info
[closeable] => 1
[visible] => 1
)
)
I need to replace one word in the array - My contracts for something else.
My contracts will be always there, but the order may change, so I must check for the exact name and replace it.
I tried it via str_replace($value, $replacement, $array);
also via
$ar = array_replace($ar,
array_fill_keys(
array_keys($ar, $value),
$replacement
)
);
and finally:
array_map(function ($v) use ($value, $replacement) {
return $v == $value ? $replacement : $v;
}, $arr);
Nothing worked. So how can I replace that one word?
</div>
foreach ($ar as &$item) {
if ($item['title'] === 'My contracts') {
$item['title'] = 'Some new value';
// if you're sure that record will be met ONCE
// you can add `break;` to stop looping
}
}
If you want to use array_walk
, you can approach as
$stringToFind = 'My contracts';
$stringToReplace = 'REPLACMENT';
array_walk($arr, function(&$v,$k) use ($stringToFind,$stringToReplace){
($v['title'] == $stringToFind) ? ($v['title'] = $stringToReplace) : '';
});