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:
foreach($featured as $key => $value){
echo $value['name'];
}
this outputs the same as:
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.
php arrays foreach
add a comment |
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:
foreach($featured as $key => $value){
echo $value['name'];
}
this outputs the same as:
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.
php arrays foreach
Read about PHP arrays and foreach. In your example you don't use$keyinside the foreach, so you might as well go for the simpler version.
– Rolando Isidoro
Aug 28 '13 at 16:01
Here is what the array returns:Array ( [0] => Array ( [id] => 7 [name] => Shoes 2 [thumbnail] => /images/dummy-thumb.jpg ) [1] => Array ( [id] => 1 [name] => Game 1 [thumbnail] => /images/dummy-thumb.jpg ) [2] => Array ( [id] => 9 [name] => Shirt 2 [thumbnail] => /images/dummy-thumb.jpg ) )The$keyis the[0] [1] [2]and$valueare[id] [name] [thumbnail]correct?
– handmdmr
Aug 28 '13 at 20:10
add a comment |
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:
foreach($featured as $key => $value){
echo $value['name'];
}
this outputs the same as:
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.
php arrays 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:
foreach($featured as $key => $value){
echo $value['name'];
}
this outputs the same as:
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.
php arrays foreach
php arrays foreach
edited Aug 28 '13 at 16:02
rink.attendant.6
17.5k1766112
17.5k1766112
asked Aug 28 '13 at 15:56
handmdmrhandmdmr
4032513
4032513
Read about PHP arrays and foreach. In your example you don't use$keyinside the foreach, so you might as well go for the simpler version.
– Rolando Isidoro
Aug 28 '13 at 16:01
Here is what the array returns:Array ( [0] => Array ( [id] => 7 [name] => Shoes 2 [thumbnail] => /images/dummy-thumb.jpg ) [1] => Array ( [id] => 1 [name] => Game 1 [thumbnail] => /images/dummy-thumb.jpg ) [2] => Array ( [id] => 9 [name] => Shirt 2 [thumbnail] => /images/dummy-thumb.jpg ) )The$keyis the[0] [1] [2]and$valueare[id] [name] [thumbnail]correct?
– handmdmr
Aug 28 '13 at 20:10
add a comment |
Read about PHP arrays and foreach. In your example you don't use$keyinside the foreach, so you might as well go for the simpler version.
– Rolando Isidoro
Aug 28 '13 at 16:01
Here is what the array returns:Array ( [0] => Array ( [id] => 7 [name] => Shoes 2 [thumbnail] => /images/dummy-thumb.jpg ) [1] => Array ( [id] => 1 [name] => Game 1 [thumbnail] => /images/dummy-thumb.jpg ) [2] => Array ( [id] => 9 [name] => Shirt 2 [thumbnail] => /images/dummy-thumb.jpg ) )The$keyis the[0] [1] [2]and$valueare[id] [name] [thumbnail]correct?
– handmdmr
Aug 28 '13 at 20:10
Read about PHP arrays and foreach. In your example you don't use
$key inside the foreach, so you might as well go for the simpler version.– Rolando Isidoro
Aug 28 '13 at 16:01
Read about PHP arrays and foreach. In your example you don't use
$key inside the foreach, so you might as well go for the simpler version.– Rolando Isidoro
Aug 28 '13 at 16:01
Here is what the array returns:
Array ( [0] => Array ( [id] => 7 [name] => Shoes 2 [thumbnail] => /images/dummy-thumb.jpg ) [1] => Array ( [id] => 1 [name] => Game 1 [thumbnail] => /images/dummy-thumb.jpg ) [2] => Array ( [id] => 9 [name] => Shirt 2 [thumbnail] => /images/dummy-thumb.jpg ) ) The $key is the [0] [1] [2] and $value are [id] [name] [thumbnail] correct?– handmdmr
Aug 28 '13 at 20:10
Here is what the array returns:
Array ( [0] => Array ( [id] => 7 [name] => Shoes 2 [thumbnail] => /images/dummy-thumb.jpg ) [1] => Array ( [id] => 1 [name] => Game 1 [thumbnail] => /images/dummy-thumb.jpg ) [2] => Array ( [id] => 9 [name] => Shirt 2 [thumbnail] => /images/dummy-thumb.jpg ) ) The $key is the [0] [1] [2] and $value are [id] [name] [thumbnail] correct?– handmdmr
Aug 28 '13 at 20:10
add a comment |
7 Answers
7
active
oldest
votes
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.
3
Thank you, This is the answer i was looking for. It just confuses me when I see it used this way without using the$keyinside the loop block. Just using it to represent that it's an associative array. I understood how the loop and array works. Just not why it was being used this way without using the$keyvariable. I have been messing around with it using the$keyvar to see what it returns. Thank you again :)
– handmdmr
Aug 28 '13 at 20:00
add a comment |
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.
I liked this explanation, but what if instead of wanting the value i want to know the key?
– Nmaster88
Mar 13 '16 at 15:42
add a comment |
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.
add a comment |
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
Oh boy that made a lot more sense than any of the answers, now I get the whole idea behind this :D well at least kind of :D Live long and prosper my friend
– Denislav Karagiozov
Jul 4 '17 at 10:40
add a comment |
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.
So, we set the loop this way just incase we need to know the$keyMakes sense because this is from a function in the model in codeigniter. So may need the$keyat a later time.
– handmdmr
Aug 28 '13 at 20:19
Correct. You can also use the key to change the value of that key in the array, or use it to add the data to another array using the same key.
– aynber
Aug 28 '13 at 20:27
add a comment |
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)
add a comment |
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"
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f18492784%2fdifference-between-as-key-value-and-as-value-in-php-foreach%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
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.
3
Thank you, This is the answer i was looking for. It just confuses me when I see it used this way without using the$keyinside the loop block. Just using it to represent that it's an associative array. I understood how the loop and array works. Just not why it was being used this way without using the$keyvariable. I have been messing around with it using the$keyvar to see what it returns. Thank you again :)
– handmdmr
Aug 28 '13 at 20:00
add a comment |
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.
3
Thank you, This is the answer i was looking for. It just confuses me when I see it used this way without using the$keyinside the loop block. Just using it to represent that it's an associative array. I understood how the loop and array works. Just not why it was being used this way without using the$keyvariable. I have been messing around with it using the$keyvar to see what it returns. Thank you again :)
– handmdmr
Aug 28 '13 at 20:00
add a comment |
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.
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.
edited Aug 28 '13 at 16:08
answered Aug 28 '13 at 16:01
djiangodjiango
1,3811812
1,3811812
3
Thank you, This is the answer i was looking for. It just confuses me when I see it used this way without using the$keyinside the loop block. Just using it to represent that it's an associative array. I understood how the loop and array works. Just not why it was being used this way without using the$keyvariable. I have been messing around with it using the$keyvar to see what it returns. Thank you again :)
– handmdmr
Aug 28 '13 at 20:00
add a comment |
3
Thank you, This is the answer i was looking for. It just confuses me when I see it used this way without using the$keyinside the loop block. Just using it to represent that it's an associative array. I understood how the loop and array works. Just not why it was being used this way without using the$keyvariable. I have been messing around with it using the$keyvar to see what it returns. Thank you again :)
– handmdmr
Aug 28 '13 at 20:00
3
3
Thank you, This is the answer i was looking for. It just confuses me when I see it used this way without using the
$key inside the loop block. Just using it to represent that it's an associative array. I understood how the loop and array works. Just not why it was being used this way without using the $key variable. I have been messing around with it using the $key var to see what it returns. Thank you again :)– handmdmr
Aug 28 '13 at 20:00
Thank you, This is the answer i was looking for. It just confuses me when I see it used this way without using the
$key inside the loop block. Just using it to represent that it's an associative array. I understood how the loop and array works. Just not why it was being used this way without using the $key variable. I have been messing around with it using the $key var to see what it returns. Thank you again :)– handmdmr
Aug 28 '13 at 20:00
add a comment |
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.
I liked this explanation, but what if instead of wanting the value i want to know the key?
– Nmaster88
Mar 13 '16 at 15:42
add a comment |
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.
I liked this explanation, but what if instead of wanting the value i want to know the key?
– Nmaster88
Mar 13 '16 at 15:42
add a comment |
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.
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.
edited Aug 4 '14 at 14:08
answered Aug 28 '13 at 16:05
Charaf JRACharaf JRA
6,69412239
6,69412239
I liked this explanation, but what if instead of wanting the value i want to know the key?
– Nmaster88
Mar 13 '16 at 15:42
add a comment |
I liked this explanation, but what if instead of wanting the value i want to know the key?
– Nmaster88
Mar 13 '16 at 15:42
I liked this explanation, but what if instead of wanting the value i want to know the key?
– Nmaster88
Mar 13 '16 at 15:42
I liked this explanation, but what if instead of wanting the value i want to know the key?
– Nmaster88
Mar 13 '16 at 15:42
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited Jun 11 '15 at 6:45
answered Jun 11 '15 at 6:25
Ahmad Baktash HayeriAhmad Baktash Hayeri
4,67222237
4,67222237
add a comment |
add a comment |
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
Oh boy that made a lot more sense than any of the answers, now I get the whole idea behind this :D well at least kind of :D Live long and prosper my friend
– Denislav Karagiozov
Jul 4 '17 at 10:40
add a comment |
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
Oh boy that made a lot more sense than any of the answers, now I get the whole idea behind this :D well at least kind of :D Live long and prosper my friend
– Denislav Karagiozov
Jul 4 '17 at 10:40
add a comment |
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
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
edited Feb 3 '14 at 22:00
answered Feb 3 '14 at 21:43
sargassargas
2,20532751
2,20532751
Oh boy that made a lot more sense than any of the answers, now I get the whole idea behind this :D well at least kind of :D Live long and prosper my friend
– Denislav Karagiozov
Jul 4 '17 at 10:40
add a comment |
Oh boy that made a lot more sense than any of the answers, now I get the whole idea behind this :D well at least kind of :D Live long and prosper my friend
– Denislav Karagiozov
Jul 4 '17 at 10:40
Oh boy that made a lot more sense than any of the answers, now I get the whole idea behind this :D well at least kind of :D Live long and prosper my friend
– Denislav Karagiozov
Jul 4 '17 at 10:40
Oh boy that made a lot more sense than any of the answers, now I get the whole idea behind this :D well at least kind of :D Live long and prosper my friend
– Denislav Karagiozov
Jul 4 '17 at 10:40
add a comment |
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.
So, we set the loop this way just incase we need to know the$keyMakes sense because this is from a function in the model in codeigniter. So may need the$keyat a later time.
– handmdmr
Aug 28 '13 at 20:19
Correct. You can also use the key to change the value of that key in the array, or use it to add the data to another array using the same key.
– aynber
Aug 28 '13 at 20:27
add a comment |
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.
So, we set the loop this way just incase we need to know the$keyMakes sense because this is from a function in the model in codeigniter. So may need the$keyat a later time.
– handmdmr
Aug 28 '13 at 20:19
Correct. You can also use the key to change the value of that key in the array, or use it to add the data to another array using the same key.
– aynber
Aug 28 '13 at 20:27
add a comment |
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.
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.
answered Aug 28 '13 at 16:04
aynberaynber
13.1k22743
13.1k22743
So, we set the loop this way just incase we need to know the$keyMakes sense because this is from a function in the model in codeigniter. So may need the$keyat a later time.
– handmdmr
Aug 28 '13 at 20:19
Correct. You can also use the key to change the value of that key in the array, or use it to add the data to another array using the same key.
– aynber
Aug 28 '13 at 20:27
add a comment |
So, we set the loop this way just incase we need to know the$keyMakes sense because this is from a function in the model in codeigniter. So may need the$keyat a later time.
– handmdmr
Aug 28 '13 at 20:19
Correct. You can also use the key to change the value of that key in the array, or use it to add the data to another array using the same key.
– aynber
Aug 28 '13 at 20:27
So, we set the loop this way just incase we need to know the
$key Makes sense because this is from a function in the model in codeigniter. So may need the $key at a later time.– handmdmr
Aug 28 '13 at 20:19
So, we set the loop this way just incase we need to know the
$key Makes sense because this is from a function in the model in codeigniter. So may need the $key at a later time.– handmdmr
Aug 28 '13 at 20:19
Correct. You can also use the key to change the value of that key in the array, or use it to add the data to another array using the same key.
– aynber
Aug 28 '13 at 20:27
Correct. You can also use the key to change the value of that key in the array, or use it to add the data to another array using the same key.
– aynber
Aug 28 '13 at 20:27
add a comment |
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)
add a comment |
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)
add a comment |
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)
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)
answered Aug 28 '13 at 16:05
3seconds3seconds
515
515
add a comment |
add a comment |
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"
add a comment |
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"
add a comment |
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"
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"
edited Aug 28 '13 at 16:03
answered Aug 28 '13 at 16:00
Thomas Martin KleinThomas Martin Klein
42627
42627
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f18492784%2fdifference-between-as-key-value-and-as-value-in-php-foreach%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Read about PHP arrays and foreach. In your example you don't use
$keyinside the foreach, so you might as well go for the simpler version.– Rolando Isidoro
Aug 28 '13 at 16:01
Here is what the array returns:
Array ( [0] => Array ( [id] => 7 [name] => Shoes 2 [thumbnail] => /images/dummy-thumb.jpg ) [1] => Array ( [id] => 1 [name] => Game 1 [thumbnail] => /images/dummy-thumb.jpg ) [2] => Array ( [id] => 9 [name] => Shirt 2 [thumbnail] => /images/dummy-thumb.jpg ) )The$keyis the[0] [1] [2]and$valueare[id] [name] [thumbnail]correct?– handmdmr
Aug 28 '13 at 20:10