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.
9 Answers
Well, the $key => $value in the foreach loop refers to the key-value pairs in associative arrays, where the key serves as the index to determine the value instead of a number like 0,1,2,... In PHP, associative arrays look like this:
$featured = array('key1' => 'value1', 'key2' => 'value2', etc.);In the PHP code: $featured is the associative array being looped through, and as $key => $value means that each time the loop runs and selects a key-value pair from the array, it stores the key in the local $key variable to use inside the loop block and the value in the local $value variable. So for our example array above, the foreach loop would reach the first key-value pair, and if you specified as $key => $value, it would store 'key1' in the $key variable and 'value1' in the $value variable.
Since you don't use the $key variable inside your loop block, adding it or removing it doesn't change the output of the loop, but it's best to include the key-value pair to show that it's an associative array.
Also note that the as $key => $value designation is arbitrary. You could replace that with as $foo => $bar and it would work fine as long as you changed the variable references inside the loop block to the new variables, $foo and $bar. But making them $key and $value helps to keep track of what they mean.
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.
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.
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
1Say 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.
2Sample 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
} 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)
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"
foreach($details as $key =>$values){ if($values['created_by'] != $user->id && $values['created_by'] != ''){ unset($details[$key]); }
} 1