0

I get images in a array then i read it with a foreach this are images, but how can i get also image text, my example is here:

    $slideImages = array('image/path/image1', 'image/path/image2', 'image/path/image13');
    $slideText = array('image text 1', 'image text 2', 'image text 3');

    if($slideImages) :
        echo '<ul>';

        foreach($slideImages as $slideImage) :
?>
            <li>
                <div>IMAGE TEXT</div>
                <img src="<?php echo $slideImage; ?>" />
            </li>
<?php
        endforeach;

        echo '</ul>';

    endif;

I need to embed also image text from the true position, i know how to do it with for but so is not efficient... it's something like this possible?

2
  • use the key from the first array to match the 2nd Commented Jan 20, 2015 at 20:54
  • Use SPL MultipleIterator Commented Jan 20, 2015 at 20:55

3 Answers 3

3

Assuming the keys are the same, use the $key in the foreach:

foreach($slideImages as $key => $slideImage) :
?>
            <li>
                <div>IMAGE TEXT</div>
                <img src="<?php echo $slideImage; ?>" />
                <?php echo $slideText[$key]; ?>
            </li>
<?php
endforeach;
Sign up to request clarification or add additional context in comments.

2 Comments

no need to assume, the code says the keys are the same
Yes, it also says image/path/image1 and image text 1 so I assumed it was example code.
1

You could also change the way you store the info and keep them in one multidimensional array.

$slides = array( 
    array( image => "image/path/image1", text => "image text 1"),
    array( image => "image/path/image2", text => "image text 2"),
    array( image => "image/path/image3", text => "image text 3")
);

Then you would iterate through the $slides array and just pull out the image and text for each:

foreach($slides as $slide)
{
            echo "Text:".$slide["text"];
            echo "Image Path:".$slide["image"];
}

This organizes your code a little better so you don't wind up with something crazy going on should your two arrays wind up out of sync.

Comments

0

simplified example:

 foreach($slideImages as $key=>$var){

echo $var;
echo $slideText[$key];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.