Skip to content

How to run foreach for the entire array except for one line in PHP?

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";
}
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";
}
See also  Python code snippet - How to redefine a legend in pandas?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.