I am sure that this is super easy and built-in function in PHP, but I have yet not seen it.
Here's what I am doing for the moment:
foreach($array as $key => $value) { echo $key; // Would output "subkey" in the example array print_r($value); }
Could I do something like the following instead and thereby save myself from writing "$key => $value" in every foreach loop? (psuedocode)
foreach($array as $subarray) { echo arrayKey($subarray); // Will output the same as "echo $key" in the former example ("subkey" print_r($value); }
Thanks!
The array:
Array ( [subKey] => Array ( [value] => myvalue ) )
If you have a value and want to find the key, use array_search() like this: $arr = array ('first' => 'a', 'second' => 'b', ); $key = array_search ('a', $arr); $key will now contain the key for value 'a' (that is, 'first' ).
The array_keys() function returns all the keys of an array. It returns an array of all the keys in array.
You can cast the object to an array like this: $myarray = (array)$myobject; And then, for an array that has only a single value, this should fetch the key for that value. $value = key($myarray);
key is just a variable that holds an array index. This example: var key = 7; var item = array[key]; gets you the same value as this: var item = array[7];
Use the array_search
function.
Example from php.net
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red'); $key = array_search('green', $array); // $key = 2; $key = array_search('red', $array); // $key = 1;
You can use key():
<?php $array = array( "one" => 1, "two" => 2, "three" => 3, "four" => 4 ); while($element = current($array)) { echo key($array)."\n"; next($array); } ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With