1

I'm new to PHP and would require some assistance if possible.

I have the array

array("Name" => $userName, "Age" => $userAge);

This works for one user but lets say I wanted to add multiple users that will all have a Name and Age how would I do that? Instead of passing is $userName would I have to pass it an array of user names and instead of $userage an array of user ages hence making it multidimesional?

Also for my purposes I cannot put the username and userage in an object and then simply add it to the array.

3 Answers 3

3

One way is:

array(
    array("Name" => $userName, "Age" => $userAge),
    array("Name" => $userName1, "Age" => $userAge1),
    array("Name" => $userName2, "Age" => $userAge2)
    ...
);
Sign up to request clarification or add additional context in comments.

Comments

2

Here is some sample code which should solve your problem given. The two input array, names and ages, do not need to be the same size, and the output array will insert default values ('N/A' for names, -1 for ages) where a corresponding name or age is missing.

$userNames = ['name1', 'name2', 'name3', 'name4'];
$userAges = [26,14,99];
$userNamesAndAges = [];

for ($i=0; $i < max(count($userNames), count($userAges)); $i++) {
    if (isset($userNames[$i])) {
        $userName = $userNames[$i]; 
    } else {
        $userName = 'N/A';
    }

    if (isset($userAges[$i])) {
        $userAge = $userAges[$i];
    } else {
        $userAge = -1;
    }

    $userNamesAndAges[] = [
        'Name' => $userName,
        'Age' => $userAge
    ];
}

foreach ($userNamesAndAges as $obj) {
    $name = $obj['Name'];
    $age = $obj['Age'];
    echo("Name: $name, Age: $age<br>"); 
}

Outputs:

Name: name1, Age: 26
Name: name2, Age: 14
Name: name3, Age: 99
Name: name4, Age: -1

Comments

1

Typecast the variables $userName and $userAge to array -

$userName = (array)$userName;
$userAge = (array)$userAge;

Iterate over them for further processing. It would then make no difference if the size of array was one or many.

1 Comment

How does this create an array of multiple users? It just makes an array of 1 user.

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.