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

匿名 (未验证) 提交于 2019-12-03 03:04:01

问题:

Is there a way 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.

回答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"; } 


回答2:

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


回答3:

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



回答4:

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); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!