Jump to content

echoing values from two different arrays alternating


greenheart

Recommended Posts

I have two, arrays one of titles one of descriptions. I want to echo the title in the first array followed by the first description in the second array, then echo the second title and the second description in the same way and so on up until the 10th value in each array.

 

Can someone kindly give me an example which I can use for this?

 

Thank you.

Depends on the structure of the data, providing both arrays are the same length and it's a non-associative array...

 

<?php
$titles = array("title 1", "title 2", "title 3");
$decriptions = array ("Blah... 1", "Blah... 2", "Blah... 3");

foreach($titles as $k=$title) {
   echo $title;
   echo $descriptions[$k];
}
?>

With regards to the error, it should be => not just =

 

You could instead make use of the SPL (specifically the ArrayIterator and MultipleIterator) to loop over both arrays at the same time. For example:

 

<?php

$titles       = new ArrayIterator(array("title 1", "title 2", "title 3"));
$descriptions = new ArrayIterator(array("Blah... 1", "Blah... 2", "Blah... 3"));

// Use a MultipleIterator to iterate over our two arrays at the same time!
$mit = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);
$mit->attachIterator($titles, 'title');
$mit->attachIterator($descriptions, 'desc');

foreach ($mit as $it)
{
echo '<h1>' . $it['title'] . "</h1>\n";
echo '<p>' . $it['desc'] . "</p>\n\n";
}

?>

Btw, the error with my code was down to a typo, it should have been $k=>$title, this basically creates $k as the key of the array and $title as each value, I used that logic to fetch the item out of the other array with the same index.

 

Salthe's solution is possibly the 'bettter' solution though.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.