69

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
        )

)
aksu
  • 5,221
  • 5
  • 24
  • 39
Industrial
  • 41,400
  • 69
  • 194
  • 289
  • 14
    Whats wrong with `foreach($array as $key => $value)`? Or, asked the other way around, what's the point using `foreach($array as $value)` when you actually need `$key` somewhere down the road? – Tomalak Jul 23 '10 at 12:10
  • 2
    I just thought it could be a good idea to get the key in a quick way – Industrial Jul 23 '10 at 12:12
  • 1
    But you do get it in a quick way with `foreach($array as $key => $value)`... :-) Or is the situation not that you are in a foreach loop? – Tomalak Jul 23 '10 at 12:14
  • I am in a foreach loop for sure, but what i've thought about was to not change the foreach statement, but just printing out the key. – Industrial Jul 23 '10 at 12:21
  • 4
    Every function call you could make would be less efficient than simply changing to the appropriate foreach loop construct. – Tomalak Jul 23 '10 at 13:48
  • @Tomalak: I totally agree with you. It doesn't even make sense to transform foreach loops to while loops for getting the key's name (or index) - in reverse (so the opposite of what Industrial would like to do!), it would do make sense! – Sk8erPeter Jan 09 '12 at 17:23
  • @sk8erpeter it's always a question of control over the normal loop behavior: if you want to jump certain keys due to the value of the current key, your `foreach` needs to store the value in some other variable and use conditions for the next values (therefore less efficient)... In a `while` like _vtorhonen_ posted, you only need `if($element=='jump3')next(next(next($array)))` – Armfoot Aug 14 '13 at 03:42
  • @Armfoot: I hope you're just kidding (because this argument seems like BS). I think the overhead of your `next(next(next($array)))` calls is much-much higher (therefore less efficient) than "storing the value in some other variable" and using a foreach loop in the usual `$key=>$value` form...not to mention that the code you showed is way too ugly to use it anywhere. – Sk8erPeter Aug 14 '13 at 10:15
  • @Sk8erPeter well, it's not the "storing in some other variable", it's `testing` it on subsequent array keys and `continue` to the next ones in a `foreach`... We can all be speculating how efficient one will be against the other in many different cases and how heavy a pointer shifter can be (`next`... nanoseconds difference? Algorithm efficiency is normally thought through logic) but that's not my point. My point is: you may have a different purpose for your loop, where you actually want to jump several keys according to specific ones so you don't need to worry about conditions for other keys. – Armfoot Aug 15 '13 at 07:58

9 Answers9

79

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);
}
?>
thevilledev
  • 2,367
  • 1
  • 15
  • 19
  • 5
    I want to add that you can use key() ANYWHERE but for this problem it make sense to use it in a while-loop. You can use key() in the instance of only wanting the first/current array element's key. – JRomero Nov 21 '12 at 19:50
  • 8
    @Industrial `foreach` uses the key... if you want to use foreach, do this: `foreach($array as $key => $value) { ... }` – Greg Oct 16 '13 at 15:27
48

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;
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
39
$foo = array('a' => 'apple', 'b' => 'ball', 'c' => 'coke');

foreach($foo as $key => $item) {
  echo $item.' is begin with ('.$key.')';
}
Somwang Souksavatd
  • 4,947
  • 32
  • 30
17

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

sushil bharwani
  • 29,685
  • 30
  • 94
  • 128
7

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

Dogbert
  • 212,659
  • 41
  • 396
  • 397
3

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.

Mike Lang
  • 96
  • 3
0

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)

B Rad C
  • 510
  • 2
  • 6
  • 18
0

Try this

foreach(array_keys($array) as $nmkey)
    {
        echo $nmkey;
    }
Chamandeep
  • 116
  • 2
  • 8
0

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;
}
Anthony Rutledge
  • 6,980
  • 2
  • 39
  • 44