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

PhpArrays

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

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

Solution 2 - Php

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

Solution 3 - Php

Couldn't you just unset the array...

So if I had an array where I didn't want the first instance, I could just:

unset($array[0]);

and that would remove the instance from the array.

Solution 4 - Php

If you were working with a normal array, I'd say to use something like

foreach (array_slice($ome_array, 1) as $k => $v {...

but, since you're looking at a user request, you don't have any real guarantees on the order in which the arguments might be returned - some browser/proxy might change its behavior or you might simply decide to modify your form in the future. Either way, it's in your best interest to ignore the ordering of the array and treat POST values as an unordered hash map, leaving you with two options :

  • copy the array and unset the key you want to ignore
  • loop through the whole array and continue when seeing the key you wish to ignore

Solution 5 - Php

in loop:

if ($key == 0) //or whatever
   continue;

Solution 6 - Php

Alternative way is to use array pointers:

reset($_POST['info']); //set pointer to zero
while ($value=next($_POST['info'])  //ponter+1, return value
{
  echo key($_POST['info']).":".$value."\n";
}

Solution 7 - Php

If you're willing to throw the first element away, you can use array_shift(). However, this is slow on a huge array. A faster operation would be

reset($a);
unset(key($a));

Solution 8 - Php

On a array filled with 1000 elements the difference is quite minimal.

Test:

<?php
function slice($a)
{
    foreach(array_slice($a, 1) as $key)
	{
		
	}
	
	return true;
}

function skip($a)
{
    $first = false;
	
	foreach($a as $key)
	{
		if($first)
		{
			$first = false;
			continue;
		}
	}
	
	return true;
}

$array = array_fill(0, 1000, 'test');

$t1 = time() + microtime(true);

for ($i = 0; $i < 1000; $i++)
{
	slice($array);
}

var_dump((time() + microtime(true)) - $t1);

echo '<hr />';

$t2 = time() + microtime(true);

for ($i = 0; $i < 1000; $i++)
{
    skip($array);
}

var_dump((time() + microtime(true)) - $t2);
?>

Output:

float(0.23605012893677)

float(0.24102783203125)

Solution 9 - Php

Working Code From My Website For Skipping The First Result and Then Continue.

<?php 

$counter = 0;

foreach ($categoriest as $category) { if ($counter++ == 0) continue; ?>

It is working on opencart also in tpl file do like this in case you need.

Solution 10 - Php




foreach($_POST['info'] as $key=>$value) {
if ($key == 0) { //or what ever the first key you're using is
continue;
}  else {
echo $value;
}
}

foreach($_POST['info'] as $key=>$value) { if ($key == 0) { //or what ever the first key you're using is continue; } else { echo $value; } }

Solution 11 - Php

if you structure your form differently

  <input type='text' name='quiz[first]' value=""/>
  <input type='text' name='quiz[second]' value=""/>

...then in your PHP

if( isset($_POST['quiz']) AND 
    is_array($_POST['quiz'])) {
    
    //...and we'll skip $_POST['quiz']['first'] 
    foreach($_POST['quiz'] as $key => $val){
      if($key == "first") continue;
      print $val; 
    }
}

...you can now just loop over that particular structure and access rest normally

Solution 12 - Php

How about something like this? Read off the first key and value using key() and current(), then array_shift() to dequeue the front element from the array (EDIT: Don't use array_shift(), it renumbers any numerical indices in the array, which you don't always want!).

<?php

$arr = array(

  'one' =&gt; "ONE!!",
  'two' =&gt; "TWO!!",
  'three' =&gt; "TREE",
  4 =&gt; "Fourth element",
  99 =&gt; "We skipped a few here.."

) ;

$firstKey = key( $arr ) ;
$firstVal = current( $arr ) ;

echo( "<p>OK, first values are $firstKey, $firstVal</p>" ) ;
####<del>array_shift( $arr ) ; #'dequeue' front element</del> # BAD! renumbers!
unset( $arr[ $firstKey ] ) ;  # BETTER!

echo( "<p>Now for the rest of them</p>" ) ;
foreach( $arr as $key=&gt;$val )
{
  echo( "<p>$key => $val</p>" ) ;
}

?>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaeranView Question on Stackoverflow
Solution 1 - PhpMichael StumView Answer on Stackoverflow
Solution 2 - PhpTom HaighView Answer on Stackoverflow
Solution 3 - PhpOrganic SEO ServicesView Answer on Stackoverflow
Solution 4 - PhpSean McSomethingView Answer on Stackoverflow
Solution 5 - PhpIrmantasView Answer on Stackoverflow
Solution 6 - Phpzb'View Answer on Stackoverflow
Solution 7 - PhpstaticsanView Answer on Stackoverflow
Solution 8 - PhpalexnView Answer on Stackoverflow
Solution 9 - PhpDheeraj VermaView Answer on Stackoverflow
Solution 10 - PhpShadi AlmosriView Answer on Stackoverflow
Solution 11 - PhpView Answer on Stackoverflow
Solution 12 - PhpboboboboView Answer on Stackoverflow