I have an array called $users (below), that i would like to print first_name and last_name together.
Array
(
[first_name] => Array
(
[0] => John
[1] => Tom
)
[last_name] => Array
(
[0] => McDonald
[1] => Terry
)
)
I used foreach loop but the problem is, the foreach loop print:
foreach ($users['first_name'] as $key => $first_name) {
foreach ($users['last_name'] as $key => $last_name) {
echo "$first_name ";
echo "$last_name<br />";
}
}
Result:
John McDonald --> that's what I want
John Terry --> I don't want this
Tom McDonald --> I don't want this
Tom Terry --> That's what I want
I put a break inside my foreach loop and again I don’t get the right result I want.
Note: I know how to solve this issue by using for loop but since the number of users change inside my database, I wouldn’t know how many for loop counts I need, unless I count the number of rows in array and make the for loop analysis based on that. But i am not looking to use for loop, does any one know a better way to do this?
As long as you use the value of
$key, you don’t need to predetermine the count, and indeed you don’t even need an inner loop.