[php] PHP: Get key from array?

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
        )

)

This question is related to php arrays multidimensional-array key

The answer is


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);
}
?>

Another way to use key($array) in a foreach loop is by using next($array) at the end of the loop, just make sure each iteration calls the next() function (in case you have complex branching inside the loop)


Try this

foreach(array_keys($array) as $nmkey)
    {
        echo $nmkey;
    }

$foo = array('a' => 'apple', 'b' => 'ball', 'c' => 'coke');

foreach($foo as $key => $item) {
  echo $item.' is begin with ('.$key.')';
}


$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));


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;

If it IS a foreach loop as you have described in the question, using $key => $value is fast and efficient.


If you want to be in a foreach loop, then foreach($array as $key => $value) is definitely the recommended approach. Take advantage of simple syntax when a language offers it.


Here is a generic solution that you can add to your Array library. All you need to do is supply the associated value and the target array!

PHP Manual: array_search() (similiar to .indexOf() in other languages)

public function getKey(string $value, array $target)
{
    $key = array_search($value, $target);

    if ($key === null) {
        throw new InvalidArgumentException("Invalid arguments provided. Check inputs. Must be a (1) a string and (2) an array.");
    }

    if ($key === false) {
        throw new DomainException("The search value does not exists in the target array.");
    }

    return $key;
}

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to multidimensional-array

what does numpy ndarray shape do? len() of a numpy array in python What is the purpose of meshgrid in Python / NumPy? Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray Typescript - multidimensional array initialization How to get every first element in 2 dimensional list How does numpy.newaxis work and when to use it? How to count the occurrence of certain item in an ndarray? Iterate through 2 dimensional array Selecting specific rows and columns from NumPy array

Examples related to key

How do I check if a Key is pressed on C++ Map<String, String>, how to print both the "key string" and "value string" together Python: create dictionary using dict() with integer keys? SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch How to get the stream key for twitch.tv How to get key names from JSON using jq How to add multiple values to a dictionary key in python? Initializing a dictionary in python with a key value and no corresponding values How can I sort a std::map first by value, then by key?