CreMedian
CreMedian

Reputation: 803

Echo nested foreach with no duplicates PHP

I have 2 arrays with the same amount of items. One stores a class to signify social media, the other array holds the URL that pairs with the class. They look like this:

 $array1 = ([0]=>twitter,[1]=>facebook,[2]=>linkedin);
 $array2 = ([0]=>http://www.twitter.com/username123,[1]=>http://www.facebook.com/user-name123,[2]=>http://www.linkedin.com/stuff/username123);

I want to loop through the arrays at the same time, printing the data in its respective place to create social media links. I currently have this:

foreach ($array1 as $k1=>$class){
  foreach ($array2 as $k2=>$URL){
  echo '<li><a href="'.$URL.'" class="'.$class.'">Visit Site</a></li>';
  }
}

This repeats every item twice, which I think is due to the nested foreach.

If I move the echo statement outside the nested function, it prints all the classes that I want, but will only take the last URL from that array.

How do I print a single list-item, link combo for each pairing? I have seen array_unique to remove duplicates, but I am a serious PHP n00b.

Thank you.

Upvotes: 0

Views: 1528

Answers (4)

iiro
iiro

Reputation: 3119

IMO, Eugene has the best answer. I just want to mention another way if $array1 and $array2 has different amount of items.

foreach ($array1 as $k1=>$class){
  if (isset($array2[$k1])) {
   echo '<li><a href="'.$array2[$k1].'" class="'.$class.'">Visit Site</a></li>';
  }
}

Upvotes: 1

doitlikejustin
doitlikejustin

Reputation: 6353

You could use a for loop as long as they both have the same count

$length = count($array1);
for($i=0; $i<$length; $i++)
{
    echo '<li><a href="'.$array2[$i].'" class="'.$array2[$i].'">Visit Site</a></li>';
}

Upvotes: 0

Konsole
Konsole

Reputation: 3475

You are doing it wrong. Its not necessary to use 2 arrays. Try something like

$array = array(
        'twitter' => 'http://www.twitter.com/username123',
        'facebook' => 'http://www.facebook.com/user-name123',
        'linkedin' => 'http://www.linkedin.com/stuff/username123'
     );

foreach ($array as $url=>$class){
   echo '<li><a href="'.$url.'" class="'.$class.'">Visit Site</a></li>';
}

Or use array_combine as suggested in previous answer.

Upvotes: 0

Alma Do
Alma Do

Reputation: 37365

May be that will help:

$rgLinks = array_combine($array1, $array2);
foreach($rgLinks as $sClass=>$sHref)
{
   echo('<li><a href="'.$sHref.'" class="'.$sClass.'">Visit Site</a></li>');
}

Upvotes: 2

Related Questions