print all arrary values except first value - php
I have an array of numbers. I can print all values usin开发者_C百科g for each
command in php. But what I want is, I don't want to print first value (ie, array[0]
) and want to print all other values.
foreach($array as $k=>$val){
if($k){echo $val;}
}
for brevity, i did only exactly what was asked. The first index has a value of 0
which is falsy, so the value won't get echo
ed when tested in the if
condition.
$cloneArray = $array;
array_shift($cloneArray); // will remove the first element of array
foreach($cloneArray as $key => $value){
echo $key." = ".$value;
}
this will also work if your array is in format of
array('key1' => 'value1', 'key2'=> 'value2', ...)
There are dozens..thousands of simple ways to do this. I'm going to list six:
$array = array(5, 6, 7, 8, 9);
foreach ($array as $index => $elem) {
if ($index == 0) {
continue;
}
echo $elem;
}
foreach($array as $index => $elem) {
if ($index != 0) {
echo $elem;
}
}
for ($x = 1; $x < count($array); $x++) {
echo $array[$x];
}
$keep = array_shift($array);
foreach ($array as $index => $elem) {
echo $elem;
}
array_unshift($array, $keep);
foreach (array_diff($array, array($array[0])) as $elem) {
echo $elem;
}
function print_not_zero($elem, $index) {
if ($index) {
echo $elem;
}
}
array_walk($array, 'print_not_zero');
I don't want to insult you, but as a developer you should think more critically for a moment and take the time to visualize the problem. Otherwise you might waste too much time on stackoverflow.
$i = 0
foreach($array as $single)
{
if ($i > 0)
echo $single;
$i++;
}
Although, unless you're using an associative array, a for
cycle would be better perhaps.
$i=array(0,1,2,3);
foreach($i as $key=>$value)
{
if($key!='0')
echo $value;
}
精彩评论