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 :)

Link to comment
Share on other sites

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) {

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.