Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add key value pair to existing array

Tags:

arrays

loops

php

I have an the variable $users set to an array that resembles the below

Array(
    [4] => Array(
        [userid] => 4
        [name] => Mike
        [gender] => M
    )

    [5] => Array(
        [userid] => 5
        [name] => Sally
        [gender] => F
    )

    [6] => Array(
        [userid] => 6
        [name] => Steve
        [gender] => M
    )
)

I then have code that loops through this array to call a function to calculate age.

foreach($users as $user){
    $age = getUserAge($user->id);
}

How do I take the variable $age and add it into $users to result with the follow array?

Array(
    [4] => Array(
        [userid] => 4
        [name] => Mike
        [gender] => M
        [age] => 35
    )

    [5] => Array(
        [userid] => 5
        [name] => Sally
        [gender] => F
        [age] => 24
    )

    [6] => Array(
        [userid] => 6
        [name] => Steve
        [gender] => M
        [age] => 32
    )
)
like image 967
mhopkins321 Avatar asked Dec 21 '13 04:12

mhopkins321


People also ask

How do you add a key-value pair to an array?

To add a key/value pair to all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use dot notation to add a key/value pair to the current object. The key/value pair will get added to all objects in the array.

Can array have key-value pairs?

Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well.

How do I change the value of a key in an array?

Change Array Key using JSON encode/decode It's short but be careful while using it. Use only to change key when you're sure that your array doesn't contain value exactly same as old key plus a colon. Otherwise, the value or object value will also get replaced.


2 Answers

foreach($users as &$user){
    $age = getUserAge($user['userid']);
    $user['age'] = $age;
}

Compact Version:

foreach($users as &$user){
    $user['age'] = getUserAge($user['userid']);
}

Note the ampersand before the array variable name meaning the variable is passed by reference, and so can be modified. See the docs for more info.

like image 59
chanchal118 Avatar answered Oct 21 '22 09:10

chanchal118


foreach($users as $index => $user) {
    $users[$index]['age'] = getUserAge($user['userid']);
}
like image 34
Adrian Avatar answered Oct 21 '22 08:10

Adrian