LittleJoe Posted October 22, 2013 Share Posted October 22, 2013 (edited) I need to loop through an array, in the order that the items appear, and get both the key of the item and its value. I know I can use foreach to loop through an array but as far as I know I can choose between the key and the value of the current item but not get both. Here's an example of an array: <?php$SampleArray = array(55 => "car","2" => "house","boat" => "boat",0 => "engine",666 => "website",);?> It would work somehow like this: loop($SampleArray){ echo key . " - " value . "n";} And the result would be something like:55 - car 2 - house boat - boat 0 - engine 666 - website Edited October 22, 2013 by LittleJoe Link to comment Share on other sites More sharing options...
dsonesuk Posted October 22, 2013 Share Posted October 22, 2013 you reference both the key and value varables in foreach loop and show results foreach ($SampleArray as $key => $value) { echo '<p>'.$key.' - '.$value.'</p>'; } Link to comment Share on other sites More sharing options...
justsomeguy Posted October 22, 2013 Share Posted October 22, 2013 You can also use the array_keys function to return an array of the keys, and then loop through that to get each key and use the key to reference the value in the original array. Link to comment Share on other sites More sharing options...
LittleJoe Posted October 23, 2013 Author Share Posted October 23, 2013 Thanks guys, you're the best. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now