Reputation: 35
I am working on a small "user list" system, and i need to foreach three arrays. Here is what i "want to do":
<?php
$users = array("user1", "user2");
$descriptions = array("user1 description", "user2 description");
$socials = array("skype: user1", "skype: user2");
foreach ($users as $user && $description as $description && $socials as $social) {
echo "<tr><td style=\"width:60px\"><img width=\"50\" height=\"50\" alt=\"{$user}'s profile picture\" src=\"blog/users/{$user}/avatar.png\"><br/>{$user}</td><td style=\"width:70%\">{$descriptions}</td><td style=\"text-align:left\">{$social}</td></tr>}";}
?>
How can i make this work?
Upvotes: 1
Views: 936
Reputation: 24645
You can use array_map with a null first parameter you build a multidimensional array from the three and then walk it with foreach
$combined = array_map(null, $users, $descriptions, $socials);
foreach ($combined as $user) {
$username = $user[0];
$description = $user[1];
$social = $user[2];
echo "<tr><td style=\"width:60px\"><img width=\"50\" height=\"50\" alt=\"{$username}'s profile picture\" src=\"blog/users/{$username}/avatar.png\"><br/>{$username}</td><td style=\"width:70%\">{$description}</td><td style=\"text-align:left\">{$social}</td></tr>}";
}
Upvotes: 3
Reputation: 795
$users = array("user1", "user2");
$descriptions = array("user1 description", "user2 description");
$socials = array("skype: user1", "skype: user2"); $i = 0;
foreach ($users as $user)
{
$html .= "{$user}{$descriptions[$i]}{$socials[$i]}";
$i++;
}
Upvotes: 1
Reputation: 16828
You can use the key
in the foreach
to be able to call another array (assuming that they match up):
<?php
$users = array("user1", "user2");
$descriptions = array("user1 description", "user2 description");
$socials = array("skype: user1", "skype: user2");
foreach ($users as $key=>$user) {
echo "<tr><td style=\"width:60px\"><img width=\"50\" height=\"50\" alt=\"{$user}'s profile picture\" src=\"blog/users/{$user}/avatar.png\"><br/>{$user}</td><td style=\"width:70%\">{$descriptions[$key]}</td><td style=\"text-align:left\">{$social[$key]}</td></tr>}";}
Addtionally, it is not recommended to have so many lines of code in one echo
. I prefer the heredoc
approach that "breaks" everything apart, so that you can visually read (and make changes):
foreach ($users as $key=>$user) {
echo <<<EOD
<tr>
<td style="width:60px"><img width="50" height="50" alt="{$user}'s profile picture" src="blog/users/{$user}/avatar.png"><br>{$user}</td>
<td style="width:70%">{$descriptions[$key]}</td>
<td style="text-align:left">{$social[$key]}</td>
</tr>
EOD;
}
Upvotes: 0
Reputation: 2619
Run a for loop, the go thru all 3 array at once.
for ($i = 0; $i < count($users); $i++)
{
echo $users[$i].'<br />'; //get location $i of array $users
echo $descriptions[$i].'<br />'; //get location $i of array $descriptions
echo $socials[$i].'<br />'; //get location $i of array $socials
}
Upvotes: 0