开发者

PHP Last Array Key Issue

开发者 https://www.devze.com 2023-03-11 06:12 出处:网络
I have this simple code for pasting images from a directory, I\'ve sorted them into an array but the problem I can\'t seem to work out is how to get the last array to be different.

I have this simple code for pasting images from a directory, I've sorted them into an array but the problem I can't seem to work out is how to get the last array to be different.

This is my code so far:

foreach($images as $image){
echo("{image : '$image'}, ");
}

I'm looking to keep print the single items in the 开发者_StackOverflow社区array but on the last one I'd like to not have the comma.

Any help would be great,

Thanks!


Simple.

function doit($image) {
    return "{image: '$image'}"
}

$images = array_map('doit',$images);
$images = implode(', ',$images);


echo "{image : '".implode("'}, {image : '",$images)."'}";


Try:

<?php
$buffer = array();
foreach($images as $image){
    $buffer[] = "{image : '$image'}";
}
echo implode(', ', $buffer);


Try using the key and the length of the array:

$arrLength = count($images);
foreach($images as $key=>$image){
   echo("{image : '$image'}");
   if($key < $arrLength - 1){  echo ", "; }
}

Or use an array_map:

function make_array($n)
{
    return "{image: '$n'}"
}

$map = array_map("make_array", $images);
$new_array = implode(', ', $map);


You could do this attractively with a do..while loop:

$image = current($images);
do {
    echo "{image : '$image'}";
} while (($image = next($images) && (print " ,"));

Note that you have to use print not echo there, as echo does not behave as a function.

The second part of the conditional only executes if the first part passes, so " ," will only be printed if another image exists.


If there is the possibility (as in, even the vaguest possibility) that your array may contain values that aren't non-empty strings, you'll need to be more verbose:

} while (
    (false !== ($image = next($images)) && 
    (print " ,")
);

I'm not convinced this is very readable, however, even split over multiple lines, so if this is the case I'd go for one of the other approaches.


Either use an if statement and check if it's the last and echo accordingly, or concatenate without echoing, trim the result after it's generated, and echo.


You could do if and else statements, where if its the last image print without comma else if it isn't print with comma.


$last = array_pop(array_keys($images));

foreach($images as $key => $image) {
   if ($key == $last) {
      ... last image ,don't output comma
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消