2

The problem I have is that value gets overwritten in second foreach loop. I need to set the key to image thumbnail link and set value to an image path.

$img_thumbs = array('folder/thumb1.jpg','folder/thumb2.jpg','folder/thumb3.jpg');
$img_links = array('folder/image1.jpg','folder/image2.jpg','folder/image3.jpg');

$imgs = array();

foreach($img_links as $img_val)
{       
    foreach($img_thumbs as $thum_val)
    {
        $imgs[$thum_val] = $img_val
    }
}   

print_r($imgs);

OUTPUT (notice how image value repeats the last value):

Array ( 
      ["folder/thumb1.jpg"] => ["folder/image3.jpg"],
      ["folder/thumb2.jpg"] => ["folder/image3.jpg"],
      ["folder/thumb3.jpg"] => ["folder/image3.jpg"]
)

WHAT I NEED:

Array ( 
      ["folder/thumb1.jpg"] => ["folder/image1.jpg"],
      ["folder/thumb2.jpg"] => ["folder/image2.jpg"],
      ["folder/thumb3.jpg"] => ["folder/image3.jpg"]
)

Thanks in advance

2 Answers 2

3
$imgs = array_combine($img_thumbs, $img_links);

See http://php.net/array_combine

If you absolutely wanted to do that in a loop:

foreach ($img_thumbs as $i => $thumb) {
    $imgs[$thumb] = $img_links[$i];
}
Sign up to request clarification or add additional context in comments.

2 Comments

array_combine doesn't want to accept string as a key. It is giving me illegal error. I've already tried doing that.
Very strange...I've tried array_combine before, it kept throwing illegal string error...But either way I tried both of your samples and they work like a charm. Thank you!
0

you just need to get rid of one of the foreach loops and increment the Images array by 1 each time you go through the loop

2 Comments

could you write an example of what do you mean?
I am not well versed in PHP, but it looks like @deceze has it written out properly in the second code example. I was speaking from a logic point of view.

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.