Gregor Gregor - 1 month ago 6
PHP Question

php manipulate strings in foreach loop

I would like to loop through an array with .png filenames, get the image orientation, prepend 'a' for landscape 'b' for portrait so i have them sorted for gallery output.

How can I edit the strings, while looping through the array $images ?

Thank you.

foreach ($images as $img) {
list($width, $height) = getimagesize("path/to/img" . $img);
if ($width > $height) {
// how to prepend 'a' to $img?
}
else {
// how to prepend 'b' to $img?
}
}

Answer

You would have either have to pass the value by reference or use something like array map.

Pass by reference is simply adding an & before the iteration value:

foreach ($images as &$img) {

    list($width, $height) = getimagesize("path/to/img" . $img);

    $img = (($width > $height) ? 'a' : 'b') . $img;
}

Using array_map

$images = array_map(function ($img) {

    list($width, $height) = getimagesize("path/to/img" . $img);

    $img = (($width > $height) ? 'a' : 'b') . $img;

    return $img;

}, $images);

Hope this helps!