Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.