Avoid using 'explicit' loop, find / edit array with desired value

1

I have the following array:

$users = array(
    array(
        'id' => 17,
        'name' => 'Miguel'
    ),
    array(
        'id' => 23,
        'name' => 'Vera'
    ),
    array(
        'id' => 39,
        'name' => 'Sara'
    )
);

My question is: can you edit (add / edit / delete) the values of one of the arrays based on one of their values without using for/foreach/while ?

For example: I would like to add a key / value to the array whose id is 23, so that it is:

...
array(
    'id' => 23,
    'name' => 'Vera',
    'loggedin' => true
),
...

I took a look at here and in the functions that speak but do not think (at least I could not implement) that is any of them.

    
asked by anonymous 29.07.2016 / 10:57

1 answer

2

The way this array is is entirely possible. The problem is that the more dimensions, or better, the more multidimensional the array becomes, the more complicated and complex the code gets, bringing the need for looping.

In this particular case it's easy to see:

// abaixo usei o array_search para pesquisar a chave primária do array onde na sua coluna id contenha o valor setado.

// com isso podemos fazer qualquer modificação:

$users = array(
  array(
    'id' => 17,
    'name' => 'Miguel'
),
array(
    'id' => 23,
    'name' => 'Vera'
),
array(
    'id' => 39,
    'name' => 'Sara'
)
);

// exemplo de inserção

$local = array_search(23, array_column($users, 'id'));

$users[$local]['loggedin'] = true;


// exemplo de edição

$local = array_search(17, array_column($users, 'id'));

$users[$local]['name'] = "Miguelito";


// exemplo para deletar

$local = array_search(39, array_column($users, 'id'));

unset($users[$local]['name']);

print_r($users);

?>

Just to make it clear, this code is just for learning, as quoted by @miguel. I tested it with help from him to see which of the two applications run faster and the for loop on all tests ran 2x faster.

    
29.07.2016 / 19:48