It’s weird how simple things like these I cannot find about php on the internet. Without further ado, how do I find an element inside an array that already has a string index, with a position?
For example:
$array = ["apple"=>"red","raspberry"=>"blue","green","yellow"] // As you can see this is a mixed array
for($i=0;$i<=count($array);$i++){
var_dump(getelementfrompos($array,$i)) // pseudocode
}
// output
array(2) => {
[key] => string(5) "apple";
[value] => string(3) "red"
}
array(2) => {
[key] => string(9) "raspberry";
[value] => string(4) "blue"
}
array(2) => {
[key] => integer(2);
[value] => string(5) "green"
}
array(2) => {
[key] => integer(3);
[value] => string(6) "yellow"
}
DUMBED DOWN VERSION:
$array = ["apple"=>"red"]
getkeyfrompos($array,0) // returns -> "apple"
How do I find an element inside an array that already has a string index, with a position, as if it was an element with a numerical index instead?
3
Answers
Use
array_keys()
to get all the keys of the array, then index into that.I’m not entirely sure why you would want to do what you’re asking, you could use
array_values
and then do anarray_search
on the value but this would not work well for duplicate values.Perhaps, this is where you could just create a wrapper. Rather than access properties of your array with
[0]
you could access the object property with->{0}
.For example, a wrapper like this:
Could be used like this:
You can see an example working over on 3v4l.org but this seems extremely overkill. Forgive me if I’ve mistaken what your intent is but I hope this helps.
Further reading:
Use array_keys().
Your expectations were not completely clear so,
in my solution I assume that if the original
array element did not have a key, I will return NULL.
Output