Jump to content

[SOLVED] How to skip first result in array foreach loop


t_machine

Recommended Posts

Hi, I am wondering if someone could help me with this problem. I have an array that contains both key and value. The first key/value is used to store a heading so it is not needed in the rest of the loop. How can I skip that first key/value and display the rest.

 

Example:

 

$myarray = array("key1"=>"heading", "key2"=>1, "key3"=>2.......

 

Without knowing the key/value of the first result, how can I skip it

 

foreach($myarray as $k =>$v){

 

//if first key skip

 

//else continue the loop

 

}

 

Thanks in advance :)

You could try something like this:

<?php
$myarray = array("key1"=>"heading", "key2"=>1, "key3"=>2);

$head = array_shift($myarray);

foreach($myarray as $k =>$v){
    //do what you like
}
?>

 

That'll remove the first key and value and save it as $head.

Then you can go through the array without worrying about it. Afterwards you can use

array_unshift($myarray, $head);

to add it back to the beginning

 

 

EDIT: wuhtzu's idea might be simpler, although you'd need to change this bit:

  if($i <> 1) {

to this:

  if($i > 1) {

You could do something like this... Not very memory efficient tho:

 

<?php
//$array is your array

$temp = $array;
array_shift($temp);

foreach($temp as $k=>$v)
//....

?>

 

 

Alternatively you could use an if:

<?php
//$array is your array

$start = TRUE;
foreach($array as $k=>$v)
{
if($start)
	$start = FALSE;
else
	//....
}

?>

 

 

Orio.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.