Skip to content
Advertisement

How can i update or change in array using PHP

I need to update the property accessories of this JSON

{
  id: "1",
  name: "TEST",
  accessories: [
        "1",
        "2",
        "3"
  ]
}

How can I add 4 or change 3 to 4 to the accessories array?

Advertisement

Answer

//Decode JSON to PHP object
$arrr = json_decode('{
  "id": "1",
  "name": "TEST",
  "accessories": [
        1,
        2,
        3
  ]
}');

$old_value  = 3;    // The value you want to change
$new_value1 = 4;    // The value you want to change it to
$new_value2 = 100;  // A new value you want to insert into the array

$array_key = array_search($old_value, $arrr->accessories);  // Get array key of old value
$arrr->accessories[$array_key] = $new_value1;               // Update array with value

$arrr->accessories[] = $new_value2;                         // Add extra value to array

echo json_encode($arrr);             // Re-encode and print results

// Output: {"id":"1","name":"TEST","accessories":[1,2,4,100]}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement