[php] Difference between "as $key => $value" and "as $value" in PHP foreach

I have a database call and I'm trying to figure out what the $key => $value does in a foreach loop.

The reason I ask is because both these codes output the same thing, so I'm trying to understand why it's written this way. Here's the code:

1)In foreach use $key => $value

foreach($featured as $key => $value){
  echo $value['name'];
}

this outputs the same as:

2)In foreach use only $value

foreach($featured as $value) {
  echo $value['name'];
}

So my question is, what is the difference between $key => $value or just $value in the foreach loop. The array is multidimensional if that makes a difference, I just want to know why to pass $key to $value in the foreach loop.

This question is related to php arrays foreach

The answer is


if the array looks like:

  • $featured["fruit"] = "orange";
  • $featured["fruit"] = "banana";
  • $featured["vegetable"] = "carrot";

the $key will hold the type (fruit or vegetable) for each array value (orange, banana or carrot)


Sample Array: Left ones are the keys, right one are my values

$array = array(
        'key-1' => 'value-1', 
        'key-2' => 'value-2',
        'key-3' => 'value-3',
        );

Example A: I want only the values of $array

foreach($array as $value) {    
    echo $value; // Through $value I get first access to 'value-1' then 'value-2' and to 'value-3'     
}

Example B: I want each value AND key of $array

foreach($array as $key => $value) {                 
    echo $value; // Through $value I get first access to 'value-1' then 'value-2' and to 'value-3'  

    echo $key; // Through $key I get access to 'key-1' then 'key-2' and finally 'key-3'    

    echo $array[$key]; // Accessing the value through $key = Same output as echo $value;
    $array[$key] = $value + 1; // Exmaple usage of $key: Change the value by increasing it by 1            
}

here $key will contain the $key associated with $value in $featured. The difference is that now you have that key.

array("thekey"=>array("name"=>"joe"))

here $value is

array("name"=>"joe")

$key is "thekey"


Say you have an array like this:

$array = (0=>'123',1=>'abc','test'=>'hi there!')

In your foreach loop, each loop would be:

$key = 0, $value = '123'
$key = 1, $value = 'abc'
$key = 'test', $value = 'hi there!'

It's great for those times when you need to know the array key.


A very important place where it is REQUIRED to use the key => value pair in foreach loop is to be mentioned. Suppose you would want to add a new/sub-element to an existing item (in another key) in the $features array. You should do the following:

foreach($features as $key => $feature) {
    $features[$key]['new_key'] = 'new value';  
} 


Instead of this:

foreach($features as $feature) {
    $feature['new_key'] = 'new value';  
} 

The big difference here is that, in the first case you are accessing the array's sub-value via the main array itself with a key to the element which is currently being pointed to by the array pointer.

While in the second (which doesn't work for this purpose) you are assigning the sub-value in the array to a temporary variable $feature which is unset after each loop iteration.


Let's say you have an associative array like this:

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => array('x'=>123)
);

In the first iteration : $key="one" and $value=1.

Sometimes you need this key ,if you want only the value , you can avoid using it.

In the last iteration : $key='seventeen' and $value = array('x'=>123) so to get value of the first element in this array value, you need a key, x in this case: $value['x'] =123.


The difference is that on the

foreach($featured as $key => $value){
 echo $value['name'];
}

you are able to manipulate the value of each iteration's $key from their key-value pair. Like @djiango answered, if you are not manipulating each value's $key, the result of the loop will be exactly the same as

foreach($featured as $value) {
  echo $value['name']
}

Source: You can read it from the PHP Documentation:

The first form loops over the array given by array_expression. On each iteration, the value >of the current element is assigned to $value and the internal array pointer is advanced by >one (so on the next iteration, you'll be looking at the next element).*

The second form will additionally assign the current element's key to the $key variable on >each iteration.


If the data you are manipulating is, say, arrays with custom keys, you could print them to screen like so:

$array = ("name" => "Paul", "age" => 23);

foreach($featured as $key => $value){
 echo $key . "->" . $value;
}

Should print:

name->Paul

age->23

And you wouldn't be able to do that with a foreach($featured as $value) with the same ease. So consider the format above a convenient way to manipulate keys when needed.

Cheers


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 foreach

Angular ForEach in Angular4/Typescript? How to use forEach in vueJs? Python foreach equivalent Get current index from foreach loop TypeScript for ... of with index / key? JavaScript: Difference between .forEach() and .map() JSON forEach get Key and Value Laravel blade check empty foreach Go to "next" iteration in JavaScript forEach loop Why is "forEach not a function" for this object?