i need to to change the value of an element of an array
$_SESSION['developersArray'] = array(
0 => array(
'id' => 0, // This is the row id
'name' => 'a',
'gender' => 'b',
),
1 => array(
'id' => 1,
'name' => 'c',
'gender' => 'd',
),
2 => array(
'id' => 2,
'name' => 'e',
'gender' => 'f',
));
I NEED: update the array SET name=’XXXX’ WHERE id=2
i tried the following with no luck:
$input['id']='2';
foreach ($_SESSION['developersArray'] as $developer) {
if ($developer['id'] == $input['id']) {
$_SESSION['developersArray']['name'] = 'xxxx';}}
I have tried all kinds of foreach, while, implode methods pieced together from other posts but none of them deal with this specific problem. Any help would be appreciated. THanks
2
Answers
You are close, but you need to set the name attribute one level deeper in the array.
For example:
Or with a "fancy" one liner, you can do this (with PHP 7.4 or above):
If the array index and the id are the same, then you can use like this:
In general it is a good practice to use strict type as you can. So as your array stores id as an integer, you should compare with another integer with the
===
check. If your$input['id']
comes from the user, and it is a string, you can simply cast it like this:(int) $input['id']
The problem comes from this line you try to access an element of non-index
you need to fix to be like this
So after edit it would be like this