m_73
m_73

Reputation: 569

How to get in php foreach value from other array?

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?

Upvotes: 0

Views: 142

Answers (3)

Joe Hinton
Joe Hinton

Reputation: 82

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.

Upvotes: 1

user557846
user557846

Reputation:

simplified example:

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

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

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

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;

Upvotes: 3

Related Questions