i have two arrays...multi arrays **the first called location and into it (cities names) i want to get the element name but not the first or the last how to do that
location":Array (
[0] => stdClass Object ([code] => BKK [name] => Bangkok )
[1] => stdClass Object ( [code] => SIN [name] => Singapore Changi )
[2] => stdClass Object ( [code] => KUL [name] => Kuala Lumpur ) )
my code not work
<?php
foreach ($obj->location as $lo):
if (!reset(reset($lo)) and !end(end($lo))) {
echo $lo->name . ',';
}
endforeach;
?>
You could use array_slice():
$array = array_slice($obj->location, 1, -1, true); // to preserve the keys
Example: http://codepad.org/Hi4yCTXE
Also, you can use array_shift() to remove the first element, and array_pop() to remove the last. In this way, you'll remain with an array without those elements, and with the index reset
A quick and easy way may be the following:
$counter = 0;
$last = count($obj->location - 1);
foreach($obj->location as $lo) {
if($counter && $counter != $last) echo $lo->name;
$counter++;
}
Though this assumes your array is built in an order that places the first and last items truly first and last. If not, you may need to sort your array ahead of time. In PHP, what determines the first and last element in an array is the order in which it is assigned, not necessarily the key.
Remove the first and last element of your array with array_slice and then use a foreach loop to print what you want.
$newloc = array_slice($obj->location, 1, -1);
foreach($newloc as $loc)
{
echo $loc->name;
}
See PHP: Remove the first and last item of the array
Sidenote : if you're doing this on a very large array, it would be better to use array_shift and array_pop.