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")
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
trulex
  • 39
  • 1
  • 4

1 Answers1

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.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • 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 Feb 20 '18 at 23:03
  • @Anthony: PHP creates integer keys from strings containing only integers `var_dump(["1"=>"hello", "a"=>"hello"]);` – AbraCadaver Feb 21 '18 at 20:36