gibigbig Posted July 11, 2011 Share Posted July 11, 2011 I would like to call upon an array variable from its key, say for example: $array = array("value" => 1); the code: echo $array["value"]; will easily output "1" however, i when i try this code: $array["1"]; or even: $array[0]; for the first instance in the array, all outputs are empty, why is this? and is there a solution? Quote Link to comment https://forums.phpfreaks.com/topic/241631-urgent-array-question/ Share on other sites More sharing options...
teynon Posted July 11, 2011 Share Posted July 11, 2011 That's because the key was set by you to something else. You could use foreach ($array as $key=>$value) Quote Link to comment https://forums.phpfreaks.com/topic/241631-urgent-array-question/#findComment-1241096 Share on other sites More sharing options...
Pikachu2000 Posted July 11, 2011 Share Posted July 11, 2011 Because $array["1"] and $array[0] don't exist, according to the way you've defined the array, only $array["value"] does. Quote Link to comment https://forums.phpfreaks.com/topic/241631-urgent-array-question/#findComment-1241097 Share on other sites More sharing options...
.josh Posted July 11, 2011 Share Posted July 11, 2011 Associative arrays do have an order, but it is ordered internally...and I'm pretty sure internally they have numerical references...dunno why there is no native way to refer to it. If you are just trying to loop through them, then use a foreach loop as already suggested. But if you are wanting to target an individual one, like "show me the 3rd one in the list", you can make a function easy enough to simulate it: $array = array( 'a' => 'apple', 'b' => 'banana', 'c' => 'coconut' ); function getValueByNumber($array,$pos) { if ( ($pos < 0) || ($pos > (count($array)-1)) ) return false; $c = 0; reset($array); while ($c < $pos) { next($array); $c++; } return current($array); } // following the convention that numeric indexes start at 0... echo getValueByNumber($array,2); // output: coconut Quote Link to comment https://forums.phpfreaks.com/topic/241631-urgent-array-question/#findComment-1241105 Share on other sites More sharing options...
Psycho Posted July 11, 2011 Share Posted July 11, 2011 Rather than looping through each element, it may be more efficient to just start with the one you are looking for: function getValueByNumber($array,$pos) { if ( ($pos < 0) || ($pos > (count($array)-1)) ) return false; return current(array_slice($array, $pos, 1)); } Quote Link to comment https://forums.phpfreaks.com/topic/241631-urgent-array-question/#findComment-1241111 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.