Students Empire

Learn Something New
Home

Learn PHP


array foreach loop


foreach is a special kind of looping statement that works only on arrays and objects.


retrieve just the value of each element, or


retrieve the element's key and value.


              foreach ( $array as $value ) { 
               // (do something with $value here) 
            } 
            // (rest of script here)  
            

Syntax to get key and value


              foreach ( $array as $key =>  $value ) { 
               // (do something with $key and/or $value here 
            } 
            // (rest of script here) 
            

              <?php
               $authors = array( "java", "php", "css", "html" ); 

               foreach ( $authors as $val ) { 
                   echo $val . "\n"; 
               }   
            ?>
            

              <?php 
            $myBook = array( "title" =>  "Learn PHP", 
                            "author" =>  "studentsempire.com", 
                            "pubYear" =>  2018 ); 

            foreach ( $myBook as $key =>  $value ) { 
               echo "$key  \n"; 
               echo "$value \n"; 
            } 
            ?>
            

PHP Change Array Values with foreach


When using foreach, the values inside the loop are copies of the values.


If you change the value, you're not affecting the value in the original array. The following example code illustrates this:


              <?php
            $authors = array( "java", "php", "css", "html" ); 

            // Displays "Java PHP Javascript HTML"; 
            foreach ( $authors as $val ) { 
               if ( $val == "css" ) $val = "javascript"; 
               echo $val . " "; 
            } 

            print_r ( $authors );   
            ?>
            

To modify the array values, we need to get foreach() to return a reference to the value in the array, rather than a copy.


To work with references to the array elements, add a &(ampersand) symbol before the variable name within the foreach statement:


foreach ( $array as & $value ) {}


              <?php
             $authors = array( "java", "php", "css", "html" ); 
             foreach ( $authors as  & $val ) { 
               if ( $val == "css" ) $val = "javascript"; 
               echo $val . " "; 
             } 
             unset( $val ); 
             print_r ( $authors );   
            ?>
            

The unset($val) ensures that the $val variable is deleted after the loop has finished.