Search code examples
phparrayskey-valuekeyvaluepair

Grabbing an array value by it's key


I would like to start off by saying that I have looked a good amount for this solution, but all I find is the opposite. That is, I'm trying to figure out how to get the value attached to a certain key in the array, but all I can find is grabbing the key by using the value.

Because I can't find this, I am very tempted to believe that it is a very simple problem, yet I cannot figure it out. I have looked at the array documentation, and all I've found is a method using "current," which will not work for me here.

Let's say I have an array of arrays which have distinct keys, like this:

$naEUS["A.1.5.3"] = array( 1000 , 879 , 192 );
$naEUS["A.1.5.4"] = array( 1012 , 922 , 456 );

What my goal is, is to do something like:

$var = "A.1.5.3";
$goal = $naEUS[$var];

I do hope it's not something silly, because I've already had one of those today. And please try to remember that, if it is, there is no such thing as a stupid question, just stupid people who don't ask. I'm just trying to learn here.

I'm trying to avoid any loops, if possible.

Edit1: Evidently this is how you do it, must be something else wrong on my end. Thanks for all the help and I will post my fix when I figure it out.

Edit2: This example is a little less complex than my actual code, I was just assigning $var to something wrong a bit further up.


Solution

  • Running

    $naEUS["A.1.5.3"] = array( 1000 , 879 , 192 );
    $naEUS["A.1.5.4"] = array( 1012 , 922 , 456 );
    
    $var = "A.1.5.3";
    $goal = $naEUS[$var];
    
    var_dump($goal);
    

    returns:

    array(3) { [0]=> int(1000) [1]=> int(879) [2]=> int(192) }
    

    What were you looking for?