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> }}– Rodrigo Tognin
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> }}
– Miguel
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...– Rodrigo Tognin
Try it like this:
$users[2]['loggedin'] = 'true';
– Rodrigo Tognin
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– Miguel
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– Rodrigo Tognin
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
– Miguel
A "plus" in your @miguel question would be: What’s faster? Thinking of an array with 1000 records for example.
– Andrei Coelho
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
@miguel surely loop is much easier to apply. But say which one would be faster to run? In the same application.
– Andrei Coelho
It was a matter of testing... Nothing much, having the two alternatives track the running time of each of them and compare @Andreicoelho
– Miguel
How do you do it? @miguel
– Andrei Coelho
Let’s go continue this discussion in chat.
– Miguel