Jump to content

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/241631-urgent-array-question/
Share on other sites

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 

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));
}

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.