If I have:
$array = array( \'one\' =>\'value\', \'two\' => \'value2\' );
how do I get the string one
back from $ar
Or if you need it in a loop
foreach ($array as $key => $value)
{
echo $key . ':' . $value . "\n";
}
//Result:
//one:value
//two:value2
If it is the first element, i.e. $array[0]
, you can try:
echo key($array);
If it is the second element, i.e. $array[1]
, you can try:
next($array);
echo key($array);
I think this method is should be used when required element is the first, second or at most third element of the array. For other cases, loops should be used otherwise code readability decreases.
You don't. Your array doesn't have a key [1]
. You could:
Make a new array, which contains the keys:
$newArray = array_keys($array);
echo $newArray[0];
But the value "one" is at $newArray[0]
, not [1]
.
A shortcut would be:
echo current(array_keys($array));
Get the first key of the array:
reset($array);
echo key($array);
Get the key corresponding to the value "value":
echo array_search('value', $array);
This all depends on what it is exactly you want to do. The fact is, [1]
doesn't correspond to "one" any which way you turn it.