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";
}
Are there any code examples left?
New code examples in category PHP
-
PHP 2022-03-27 22:40:03 index:of curiosa 2019 mp4
-
PHP 2022-03-27 22:35:13 Dijkstra’s algorithm php
-
PHP 2022-03-27 22:35:12 get_declared_classes
-
PHP 2022-03-27 22:30:23 php move index of a value to first position in array
-
PHP 2022-03-27 22:25:01 wordpress get_date
-
PHP 2022-03-27 21:30:38 php shorten string with dots
-
PHP 2022-03-27 21:10:46 php header 500
-
PHP 2022-03-27 21:05:06 laravel schedule run
-
PHP 2022-03-27 20:25:12 Get page title, excerpt or content by id
-
PHP 2022-03-27 20:00:27 php convert date from dd/mm/yyyy to yyyy-mm-dd