开发者

Get all elements in array besides the first one.. ? (php)

Is there a wa开发者_运维百科y to specify getting all but the first element in an array? I generally use foreach() to loop through my arrays.

say array(1,2,3,4,5), i would only want 2, 3, 4 ,5 to show and for it to skip 1.


$arr = array(1,2,3,4,5);
$all_but_the_first_element_array = array_slice($arr, 1);


There are multiple ways of approaching this problem.

The first solution is to use a flag boolean to indicate the first element and proceed in your foreach

$firstElement = true;

foreach($array as $key => $val) {
  if($firstElement) {
    $firstElement = false;
  } else {
    echo "$key => $val\n";
  }
}

If your elements are naturally numerically indexed, you do not need the boolean flag, you can simply check if the key is 0.

foreach($array as $key => $val) {
  if($key === 0) continue;      

  echo "$key => $val\n";
}

The second way is to cheat your way into a naturally numerically indexed array if it isn't already. I will use array_keys() to get a naturally numerically indexed array of keys and loop it.

$keys = array_keys($array);

foreach($keys as $index => $key) {
  if($index === 0) continue;   

  $val = $array[$key];
  echo "$key => $val\n";
}

The third way is to use the array internal pointer to skip the first element and then continue in a loop by using reset(), next(), list(), and each(). Performance and resource-wise, this is the best option. Maintainability suffers greatly though.

reset($array); // Reset pointer to 0
next($array);  // Advance pointer to 1

while (list($key, $val) = each($array)) {
  echo "$key => $val\n";
}  

If you don't mind losing the first element of the array, you can array_shift() it.

array_shift($array);

foreach($array as $key => $val) {
  echo "$key => $val\n";
}

You can also array_slice() the array. I'm also using count() in order to be able to set the preserve_keys parameter to true.

$sliced = array_slice($array, 1, count($array)-1, true);

foreach($sliced as $key => $val) {
  echo "$key => $val\n";
}


array_shift()

http://us2.php.net/manual/en/function.array-shift.php

example used in the site:

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?> 

The above example will output:

Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)

**remember that the pointer to the array is reset (new value) after the shift


Well, there can be many ways for that as we have great deal of array-manipulation functions available. However i use the following method for that:

$orig_array = array(1, 2, 3, 4 ,5);
array_shift($orig_array);
print_r($orig_array);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜