开发者

how to get only last value in a foreach? php

foreach ($data['data'] as $data) { 
 echo $data['title'][0]; 
 //echo '<br />';
}

this will print out:

melon
apple
... 
banana
pear

Now, how to jump all, only get the last value in a foreach? on开发者_Go百科ly need pear. Thanks.


If you only need the last value, then you don't need to loop. You can use end():

$lastItem = end($data['data']);
echo $lastItem['title'][0];

Note that this will set the internal array pointer to the last element. It might be necessary that you call reset($data) afterwards.


End has already been suggested (which I can recommend actually), however if you want to do it with foreach, you could do:

foreach ($data['data'] as $data) {
}
echo $data['title'][0]; 
//echo '<br />';

but this is really superfluous. You iterate over the array then only to store the last element into $data. So if there are no elements in 'data' at all this will fail (as with end, but end will return a false if the array is empty).

So go for:

$data=end($data['data']);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜