Difference between “as $key => $value” and “as $value” in PHP foreach












44















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.










share|improve this question

























  • 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


















44















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.










share|improve this question

























  • 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
















44












44








44


17






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.










share|improve this question
















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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 $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





















  • 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



















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














7 Answers
7






active

oldest

votes


















66














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.






share|improve this answer





















  • 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



















15














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.






share|improve this answer


























  • 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



















8














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.






share|improve this answer

































    7














    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






    share|improve this answer


























    • 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



















    3














    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.






    share|improve this answer
























    • 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



















    2














    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)






    share|improve this answer































      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"






      share|improve this answer

























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


        }
        });














        draft saved

        draft discarded


















        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









        66














        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.






        share|improve this answer





















        • 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
















        66














        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.






        share|improve this answer





















        • 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














        66












        66








        66







        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.






        share|improve this answer















        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.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        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 $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














        • 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








        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













        15














        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.






        share|improve this answer


























        • 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
















        15














        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.






        share|improve this answer


























        • 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














        15












        15








        15







        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.






        share|improve this answer















        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.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        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



















        • 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











        8














        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.






        share|improve this answer






























          8














          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.






          share|improve this answer




























            8












            8








            8







            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.






            share|improve this answer















            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.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jun 11 '15 at 6:45

























            answered Jun 11 '15 at 6:25









            Ahmad Baktash HayeriAhmad Baktash Hayeri

            4,67222237




            4,67222237























                7














                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






                share|improve this answer


























                • 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
















                7














                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






                share|improve this answer


























                • 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














                7












                7








                7







                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






                share|improve this answer















                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







                share|improve this answer














                share|improve this answer



                share|improve this answer








                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



















                • 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











                3














                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.






                share|improve this answer
























                • 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
















                3














                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.






                share|improve this answer
























                • 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














                3












                3








                3







                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.






                share|improve this answer













                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.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                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 $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



















                • 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

















                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











                2














                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)






                share|improve this answer




























                  2














                  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)






                  share|improve this answer


























                    2












                    2








                    2







                    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)






                    share|improve this answer













                    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)







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Aug 28 '13 at 16:05









                    3seconds3seconds

                    515




                    515























                        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"






                        share|improve this answer






























                          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"






                          share|improve this answer




























                            1












                            1








                            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"






                            share|improve this answer















                            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"







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Aug 28 '13 at 16:03

























                            answered Aug 28 '13 at 16:00









                            Thomas Martin KleinThomas Martin Klein

                            42627




                            42627






























                                draft saved

                                draft discarded




















































                                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.




                                draft saved


                                draft discarded














                                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





















































                                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







                                Popular posts from this blog

                                Tonle Sap (See)

                                I get strange results when I access the Sqlitedatabase with Unity C# via XAMPP

                                Guatemaltekische Davis-Cup-Mannschaft