PHP Foreach Loop and Switch statement example

This is a very simple PHP array example. We'll also look at how to create a switch statement in PHP to check the value of a variable inside our loop.

The output generated by the code below is displayed on the right.


//This is our associative array of fruit and veggies
$items = array(
'Apple' => 'Fruit', 
'Banana' => 'Fruit',
'Onion' => 'Veggie',
'Spinach' => 'Veggie',
'Peach' => 'Fruit',
'Carrot' => 'Veggie',
'Grape' => 'Fruit');

//Create an html table
echo "<table border='1' cellpadding='10'>
        <tr style='background-color: #999; color: #fff;'>
    <tbody> ";

        //We'll use a foreach loop to create our table rows
        foreach($items AS $item => $value) {

            //We'll use a switch statement to check each item type
            switch ($value) {

                //Check if item is a fruit and give the style variable a value
                case 'Fruit':
                    $style = 'style="background-color: #28a745; color: #fff;"';

                //Check if item is a veggie and give the style variable a different value
                case 'Veggie':
                    $style = 'style="background-color: #17a2b8 ; color: #fff;"';
                //We could have a default if we wanted, to apply if item is neither fruit nor veggie
                    # code...

            echo "<tr ".$style.">


        //Close the table body and the table
        echo "</tbody>



Type Item
Apple Fruit
Banana Fruit
Onion Veggie
Spinach Veggie
Peach Fruit
Carrot Veggie
Grape Fruit

Add new comment

The content of this field is kept private and will not be shown publicly.
Target Image