t_machine Posted October 29, 2007 Share Posted October 29, 2007 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 Quote Link to comment Share on other sites More sharing options...
Wuhtzu Posted October 29, 2007 Share Posted October 29, 2007 A real simple use would be to add a counter: <?php $i = 1; foreach($myarray as $k =>$v){ if($i <> 1) { //Do stuff to all but the first record } $i++; } ?> Quote Link to comment Share on other sites More sharing options...
Dragen Posted October 29, 2007 Share Posted October 29, 2007 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) { Quote Link to comment Share on other sites More sharing options...
Orio Posted October 29, 2007 Share Posted October 29, 2007 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. Quote Link to comment Share on other sites More sharing options...
t_machine Posted October 29, 2007 Author Share Posted October 29, 2007 Thank you all very much I figured there was a function to skip it but I wasn't sure which it was. Thanks again. Quote Link to comment Share on other sites More sharing options...
Wuhtzu Posted October 29, 2007 Share Posted October 29, 2007 Please let the rest of us know what you finally did... Quote Link to comment Share on other sites More sharing options...
t_machine Posted October 29, 2007 Author Share Posted October 29, 2007 Sorry about that, I went with the first reply using the $i counting. Thanks again Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.