PHP: Loops, functions, and server-side includes

Now that variables, ways of comparing variables, and conditional logic, let’s step it up a little and look at looks and functions.

PHP has ‘do’ loops, ‘do while’ loops, and ‘for’ loops.  Let’s look at a quick example

<?php
    $names = array('Joe','Steve','Jen','David');

    for($i=0; $i < count($names); $i++){
        echo $names[$i] . "n";
    }
?>

In the above example, I am looping through the names array and outputting each name.  There is an alternative to this particular loop, though …

<?php
    $names = array('Joe','Steve','Jen','David');

    foreach ($names as $name) {
        echo $name."n";
    }
?>

You’ll notice that the alternative doesn’t bother with the index.  It just works with each individual value in the array.

Next, let’s go over how to create and use functions in PHP.  Functions help to compartmentalize your code.  This aids in readability and re-usability.  You can define a new function like this

<?php
    //Define the function
    function FahrenheitToCelsius($degrees) {
        return ($degrees - 32) * (5 / 9);
    }

    //Call the function
    echo FahrenheitToCelsius(80);
?>

Now that you have the ability to define and use functions in your code, you need somewhere to put your function definitions.  You do not want to have to put the function definition inside of each file that needs to call the function.  One option is to put your definitions inside of a common PHP file and include it in other pages.  You can include a file by using ‘include’, ‘include_once’, ‘require’, or ‘require_once’.

So, what does an include statement look like?

<?php
    include './shared/footer.php';
?>

So, what does ‘include_once’ do?  If there are multiple instances of ‘include_once’ of a particular file, it will only include it once.  With both ‘include’ and ‘include_once’, if the included file can not be found, it will continue with parsing the remainder of the parent document.  What if you do not want it to do that?  You could use ‘require’ and ‘require_once’.  With ‘require’, a failure to include the file causes a fatal error.

 

Leave a Reply

Your email address will not be published.