1

beginner programmer here.

I have pictures in a directory that are pushed into an array

$pressImages = scandir('img/press');

then sliced to remove system files

$slice = array_slice($pressImages, 3);

then run through a loop to print out each image on to the webpage

foreach ($slice as $image) {
 echo "<div class='press list-item'><img src='img/press/$image' /></div>";
}

I would like to add anchor tags to the first four iterations of the loop (each Link is unique), but not to the others. I'm trying to learn how to consolidate instructions to the smallest number possible. Would I need to create two separate loops here? I was thinking I would create two directories, one for images that have links, and the other for images without links, with each having their own foreach loop, but my intuition suggests there might be a more efficient way.

Thanks for the help in advance!

**Some wonderful suggestions everyone thanks again, learning so much. I've been unable to try these out myself so am relying on visualizing them. I will be sure to select an answer soon

2
  • also you dont have to assign value after array_slice use the same $pressImages as it slices that array so as to reduce variables Commented Nov 29, 2016 at 15:08
  • @Rohitshah thanks very helpful did not think of that Commented Nov 30, 2016 at 0:53

4 Answers 4

1

You can do this "functional style" with array_walk:

array_walk($images, function ($image, $_, &$count) {
    $count += 1;

    $image = "<img src='img/press/$image'/>";

    if ($count <= 4) {
        $image = "<a href='#'>$image</a>";
    }

    echo "<div class='press list-item'>$image</div>", PHP_EOL;
}, 0);

You can notice that I have used only if without else. It is a good practice in PHP (and many other languages). For example, you should take a look at such great tool as PHP Mess Detector. There is a rule about this:

An if expression with an else branch is never necessary. You can rewrite the conditions in a way that the else is not necessary and the code becomes simpler to read. To achieve this use early return statements. To achieve this you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations.

And here is a working demo of my solution.

PHP_EOL in the echo is added only for the purpose of result presentation. Feel free to remove it.

Also, be aware that you cannot always rely on array key as on counter. Off the top of head example would be when you need to sort images, then the indexes won't be in order.

ADDITION:

If you have two arrays: $images and $links, and they can be linked with the order of appearance, then you can use array_map

array_map(function ($image, $link) {
    $image = "<img src='img/press/$image'/>";

    if ($link) {
        $image = "<a href='$link'>$image</a>";
    }

    // Or you can return string here and array_map will 
    // create an array of all resulting images.
    echo "<div class='press list-item'>$image</div>", PHP_EOL;
}, $images, $links);

The reason to use array_map is that you can supply more than one array and traverse them in parallel.

Here is working demo.

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting way of attacking this. Could we use the same counter like stated above to deal with the fact that the links are unique? See my comments on thmspl's answer. Thank you!
@fd1247, if you have two arrays and your approach is: n links from the array of length n go for first n images from the array of images, then you don't need counter at all.
1

UPDATED

You can use foreach key instead like this (see Official PHP foreach docs):

foreach ($slice as $key => $image) {
    if($key > 3) {
        echo "<div class='press list-item'><img src='' /></div>";
    } else {
        echo "<a href='your_link_here'><div class='press list-item'><img src='img/press/$image' /></div></a>";
    }
}

Hope this helps!

3 Comments

This is just an alternative to using array_slice and does not answer the question, which is about altering the html for the 1st 4 items in the array
Updated my answer!
I like this answer in my head. But I should of specified anchor tags so the image is clickable, not different file paths. How would you do this with unique anchor hrefs? (Editing OP to say anchor tags)
0

Is the link everytime the same?

foreach ($slice as $count => $image) {
    if($count > 3){
        echo "<div class='press list-item'><a href='#'><img src='img/press/$image' /></a></div>";
    }else{
        echo "<div class='press list-item'><img src='img/press/$image' /></div>";
    }
}

If I undstand your question correctly this would work for you.

2 Comments

The links would be different for each one, I'll add that to the initial question thanks for the clarification!
Same as Saumyas idea, i think I like this. But the urls are unique. What do you two think of adding the urls into an array, and using a counter variable to select the proper link path respective to the current iteration (iteration 2 picks link in index 1).
0

Simply add a counter that you increment, and use an if block:

$count = 0;
foreach ($slice as $image) {
    $count++;
    if($count <= 4){
        echo 'your link html here';
    }else{
        echo 'your non link html here';
    }
}

Or slightly shorter:

$count = 4;
foreach ($slice as $image) {
    if($count--){
        echo 'your link html here';
        break;
    }
    echo 'your non link html here';
}

1 Comment

The second loop will run only once. I guess continue; was meant instead of break;.

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.