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

Asked

Viewed 88 times

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 edit (add/edit/delete), the values of one of the arrays based on one of its values without using the for/foreach/while?

For example: I would like to add a key/value to the array whose id is 23 in order to stay:

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

I’ve been taking a look here and in the functions they speak of but do not think (at least I could not implement) that any of them.

  • I believe that there would have to be a loop at least in the first array, then in the second you locate the key by the function array_key_exists. Foreach($users as $arr => $value) { if array_key_exists('23', $arr) { <does what is needed> }}

  • Yes that I know how to do, I wanted to know (out of curiosity) if I could do without... But obgado @Rodrigotognin. PS: Even that was not necessary, it was enough: foreach($users as $arr => $valor) { if($valor['id'] == 23) { <faz o que é necessário> }}

  • Has the function array_push , it accepts to insert item at the end of an array but does not let indicate key, as you want...

  • Try it like this: $users[2]['loggedin'] = 'true';

  • Yes I know @Rodrigotognin. But what if I don’t know the main key? If I don’t know this array is in the index 1... Remember that you start from 0 :P

  • Truth... I remembered only now that it starts in 0... But then, if you do not know the key there complicates, because there is no way to access the specific user’s array without knowing. Or save another array only with the keys as indexes, but that would be redundancy. I prefer to use one foreach even, rsrsrs

  • Yes I also lol, probably even if there is an alternative way in a real project probably continued to do so within a loop... It’s just out of curiosity

  • A "plus" in your @miguel question would be: What’s faster? Thinking of an array with 1000 records for example.

  • Yes, I know, but as I say above it is for didactic reasons only (curiosity), I will probably continue to do as I always did, with a loop @Andreicoelho

  • @miguel surely loop is much easier to apply. But say which one would be faster to run? In the same application.

  • It was a matter of testing... Nothing much, having the two alternatives track the running time of each of them and compare @Andreicoelho

  • How do you do it? @miguel

Show 8 more comments

1 answer

2


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

In this specific case it is 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 be clear, this code is for learning only, as @miguel quoted. I did some tests with his help to know which of the two applications run faster and the loop for in all tests ran 2x faster.

  • Totally impossible?! But you managed... It was just wanted, to do it without making one loop explicitly. Obgado Andrei

  • Thanks for the @miguel! challenge actually, I learned a lot and wondered about more things.

  • This gave perfectly to answer my question. But if you like challenges, I have another: This only applies to the first occurrence of id = 23 if we have more ids that are 23 and we wanted to edit in all? How would you do it? Without using the same loops.

  • Good idea @miguel will think of how to do

  • I saw your message in the chat but I could answer... Yes this is the way to measure the execution time of a program

Browser other questions tagged

You are not signed in. Login or sign up in order to post.