13

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
    )
)

2 Answers 2

18
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Use $user["userid"] since its an array not an object
11
foreach($users as $index => $user) {
    $users[$index]['age'] = getUserAge($user['userid']);
}

1 Comment

This method worked for me where the above didn't, since the &$ was messing with other aspects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.