Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip the 1st key in an array loop?

Tags:

arrays

php

I have the following code:

if ($_POST['submit'] == "Next") {     foreach($_POST['info'] as $key => $value) {         echo $value;     } } 

How do I get the foreach function to start from the 2nd key in the array?

like image 955
aeran Avatar asked Dec 16 '08 14:12

aeran


People also ask

How do you skip the first element of an array?

You can use array. slice(0,1) // First index is removed and array is returned. FIrst index is not removed, a copy is created without the first element. The original array is not modified.

How do I find the first key of an array?

Starting from PHP 7.3, there is a new built in function called array_key_first() which will retrieve the first key from the given array without resetting the internal pointer. Check out the documentation for more info. You can use reset and key : reset($array); $first_key = key($array);

How do I remove a key from an array?

Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.


2 Answers

For reasonably small arrays, use array_slice to create a second one:

foreach(array_slice($_POST['info'],1) as $key=>$value) {     echo $value; } 
like image 126
Michael Stum Avatar answered Oct 08 '22 13:10

Michael Stum


foreach(array_slice($_POST['info'], 1) as $key=>$value) {     echo $value; } 

Alternatively if you don't want to copy the array you could just do:

$isFirst = true; foreach($_POST['info'] as $key=>$value) {     if ($isFirst) {         $isFirst = false;         continue;     }        echo $value; } 
like image 34
Tom Haigh Avatar answered Oct 08 '22 11:10

Tom Haigh