Say, if I have a PHP array:
$arr = array(
"a"=>"value a",
"b"=>"value b",
"0"=>"value 0",
"1"=>"value 1",
);
and if I want to retrieve the element at index 0, how would I do that?
Other answers clearly didn't read it. This solution will work for you:
echo $arr[array_keys($arr)[0]];
And here's an Example
References
You could even use array_values() to get the first element:
echo array_values($arr)[0];
You could even alternatively do this:
$keys = array_keys($arr);
echo $arr[$keys[0]];
Basically, array_keys() fetches the keys (which in this example would be 'a','b','0','1') and stores them in the array. Allowing you to access the very first item via $keys[0] to access the first key (Being a).
This solution is purely based off @mario's comment as it is a completely viable method of achieving what you require!
Alternatively, you could use reset() and current() to acheive this, where reset() sets the index to the very first element in your array, and current() shows the current element in that array, which would be the first, due to the reset.
reset($arr);
echo current($arr);
References
These are the ways in which you'll be able to achieve what you desire. As you won't know what the very first array elements' index is.
"0" => "value 0". "At index 0" could refer to element "value a" (the first element in order) or to element "value 0" (element whose key is 0), depending how you interpret the question. There is no need (or, indeed, any basis) for belittling others."at index 0" (meaning the very first element), not "for index 0" as you've just perceived. I agree with you about it being ambiguous, but if you read it and take it in, you'll see exactly what he was asking for.There is no "index 0" in your case because PHP arrays internally are not arrays in the original sense, but kind of an ordered hashmap. But you can use array_values to get a 0-indexed array:
$element = array_values($array)[0];
This is a generic solution for all indexes. For the first and the last element, it's faster to use reset and end if you can live with the side effect of changing the internal array pointer:
$first = reset($array);
$last = end($array);
To set an array to its values you should use "array_values", but you would lose the keys.
I would suggest to save your keys first
$keys = array_keys($arr);
Then use
array_values($arr);
Your result is really a flat array where you can use the index to get the values
$arr = array(
"value a",
"value b",
"value 0",
"value 1",
);
After your done you can combine the keys back with the array
$restored = array_combine($keys, $arr);
The above solutions will help you but the one more alternative solution is=>
foreach($array as $key=>$value)
{
if($value==0)
{
$new_array[]=$key;
}
}
new array will have key with 0 index.
$arr["0"]?0specifically there isreset(). For any other case: convert it to an indexed array first.