PHP: Get key from array?

PhpArraysMultidimensional ArrayKey

Php Problem Overview


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
        )

)

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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;

Solution 3 - Php

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

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

Solution 4 - Php


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


Solution 5 - Php

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

Solution 6 - Php

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.

Solution 7 - Php

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)

Solution 8 - Php

Try this

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

Solution 9 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIndustrialView Question on Stackoverflow
Solution 1 - PhpvtorhonenView Answer on Stackoverflow
Solution 2 - PhpSarfrazView Answer on Stackoverflow
Solution 3 - PhpSomwang SouksavatdView Answer on Stackoverflow
Solution 4 - Phpsushil bharwaniView Answer on Stackoverflow
Solution 5 - PhpDogbertView Answer on Stackoverflow
Solution 6 - PhpMike LangView Answer on Stackoverflow
Solution 7 - PhpB Rad CView Answer on Stackoverflow
Solution 8 - PhpChamandeepView Answer on Stackoverflow
Solution 9 - PhpAnthony RutledgeView Answer on Stackoverflow