• Status: Solved
• Priority: Medium
• Security: Public
• Views: 527

# Get value from associative array without key...

Given an array like this, where I don't know the key name, how can I extract the value of both elements (AL, Alabama)?

Array
(
[abbreviation] => AL
[full_name] => Alabama
)

0
interclubs
• 2
• 2
1 Solution

Software Engineer IICommented:
you cannot unless you know the array variable's name in which case you would extract the values like \$name['abbreviation']['full_name'];
0

Commented:
If you mean that you don't know the key names (abbreviation, full_name) you can do something like this:

foreach (\$array_name as \$value){

\$x[] = \$value;
}

That would give you an array of two elements in your example where \$x[0] = 'AL' and \$x[1] = 'Alabama'.

If you don't know the name of the actual array (\$array_name) in my example, I have no idea how you would find the values.
0

Commented:
array_keys will give you a list of the keys in an array.

If you have:

``````\$my_array = array('abbreviation' => 'AL', 'full_name' => 'Alabama');
``````

then you could use array_keys:
``````\$my_keys = array_keys(\$my_array);
``````

which would give you an array of Array ( [0] => abbreviation [1] => full_name ). You could then do
``````\$first_value = \$my_array[\$my_keys[0]];
\$second_value = \$my_array[\$my_keys[0]];
``````

Or you could convert the array to use numeric indexes instead of string indexes. One way to do this is use the sort() method. So if you have the \$my_array as defined above then you could do:
``````sort(\$my_array);
``````
Now \$my_array is Array ( [0] => Alabama [1] => AL) and you can use [0] and [1] to get the values.
``````\$first_value = \$my_array[0];
\$second_value = \$my_array[1];
``````
0

Software Engineer IICommented:
@jebpotly: Sweet, did not know about "array_keys(\$my_array);" Thanks
0

Commented:
;)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.