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.

<?php

//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'>
    <thead>
        <tr style='background-color: #999; color: #fff;'>
            <th>Type</th>
            <th>Item</th>
        </tr>
    </thead>
    <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;"';
                    break;

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

            echo "<tr ".$style.">
            <td>".$item."</td>
            <td>".$value."</td>            
            </tr>";

        }

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

?>

Output

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

Comments

PHP was the language that has the all codes on this it was good to make the all parts possible that was good to read. I need to make some project so I get best cv writing service 2019 it has the all codes about the all language on this that was useful or have knowledge on it.

Add new comment

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