skip to Main Content

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


  1. You are close, but you need to set the name attribute one level deeper in the array.

    For example:

    $input['id'] = 2;
    foreach ($_SESSION['developersArray'] as $index => $developer) {
        if ($developer['id'] === $input['id']) {
            $_SESSION['developersArray'][$index]['name'] = 'XXXX';
        }
    }
    

    Or with a "fancy" one liner, you can do this (with PHP 7.4 or above):

    array_walk($_SESSION['developersArray'], fn(array &$developer) => $developer['id'] === $input['id'] ? $developer['name'] = 'XXXX' : null);
    

    If the array index and the id are the same, then you can use like this:

    foreach ($_SESSION['developersArray'] as $index => $developer) {
        if ($index === $input['id']) {
            $_SESSION['developersArray'][$index]['name'] = 'XXXX';
        }
    }
    

    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']

    Login or Signup to reply.
  2. The problem comes from this line you try to access an element of non-index

    $_SESSION['developersArray']['name']
    

    you need to fix to be like this

    $_SESSION['developersArray'][$index]['name']
    

    So after edit it would be like this

    $input['id']='2'; 
    foreach ($_SESSION['developersArray'] as $index => $developer) {
        if ($developer['id'] == $input['id']) { 
           $_SESSION['developersArray'][$index]['name'] = 'xxxx';
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search