HerrPNut Posted February 19, 2010 Share Posted February 19, 2010 Hellow, I have an array $arr with keys and values, I can display the values if i define a key: <?php $arr = array("foo" => "bar", 12 => true); echo $arr["foo"]; // bar echo $arr[12]; // 1 ?> but i want to display all the keys from the array In this example this would be: foo and 12 Quote Link to comment https://forums.phpfreaks.com/topic/192616-get-keys-and-values-from-an-array/ Share on other sites More sharing options...
PHP Monkeh Posted February 19, 2010 Share Posted February 19, 2010 Hellow, I have an array $Data with keys and values. With a foreach I can display all the values: foreach($Data as $var) { echo $var; } but I also want to display al the keys... how can i do that? Quite easily, change your foreach() line to this: foreach($Data as $key => $var) That will allow you to use $key. Quote Link to comment https://forums.phpfreaks.com/topic/192616-get-keys-and-values-from-an-array/#findComment-1014752 Share on other sites More sharing options...
HerrPNut Posted February 19, 2010 Author Share Posted February 19, 2010 ok thanks! Your solution works perfectly Quote Link to comment https://forums.phpfreaks.com/topic/192616-get-keys-and-values-from-an-array/#findComment-1014753 Share on other sites More sharing options...
trq Posted February 19, 2010 Share Posted February 19, 2010 Or.... <?php $arr = array("foo" => "bar", 12 => true); foreach (array_keys($arr) as $k) { echo $k . "\n"; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/192616-get-keys-and-values-from-an-array/#findComment-1014765 Share on other sites More sharing options...
PravinS Posted February 19, 2010 Share Posted February 19, 2010 Also use array_flip() function. Quote Link to comment https://forums.phpfreaks.com/topic/192616-get-keys-and-values-from-an-array/#findComment-1014768 Share on other sites More sharing options...
salathe Posted February 19, 2010 Share Posted February 19, 2010 Don't use array_flip() if multiple items can have the same value... when flipped items will be lost! array_keys() is where the fun is at. Quote Link to comment https://forums.phpfreaks.com/topic/192616-get-keys-and-values-from-an-array/#findComment-1014788 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.