Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question

2 Answers 2

up vote 3 down vote accepted
$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];
}
share|improve this answer
    
array_combine doesn't want to accept string as a key. It is giving me illegal error. I've already tried doing that. –  Timur Aug 2 '13 at 18:08
    
Wut? What "illegal error"? Works just fine: 3v4l.org/eMOip –  deceze Aug 2 '13 at 18:11
    
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! –  Timur Aug 2 '13 at 18:21

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

share|improve this answer
    
could you write an example of what do you mean? –  Timur Aug 2 '13 at 18:13
1  
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. –  Malachi Aug 2 '13 at 18:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.