Skip to content

Instantly share code, notes, and snippets.

@bbatsche
Last active March 14, 2016 23:12
Show Gist options
  • Save bbatsche/e960759b69e5d41c37c6 to your computer and use it in GitHub Desktop.
Save bbatsche/e960759b69e5d41c37c6 to your computer and use it in GitHub Desktop.

PHP Crash Course

  • All code goes inside of PHP tags:

    <?php
    // code goes here
    ?>
  • Note, this is not an HTML tag; there is no closing tag to go along with it. Your PHP code will literally go between the ?s

  • You can have as many PHP tags/blocks as you need, although typically you will have one large block at the top of your file and then smaller ones intermixed with your HTML.

  • To display output use echo:

    <?php
    echo 'Hello world';
    ?>
  • To debug, use var_dump():

    <?php
    var_dump('Hello world');
    ?>
  • All variable names begin with a $, there is no keyword (var) to go along with this:

    <?php
    $message = 'Hello world';
    ?>
  • Strings with single quotes (') behave just like they did with JavaScript. You can use the dot (.) to concatenate.

    <?php
    $greeting = 'Hello';
    $name = 'Codeup';
    $message = $greeting . ' ' . $name;
    ?>
  • Double quoted strings (") allow you to put variables in the string. This is called interpolation. It is generally good practice to wrap interpolated variables in curly braces ({}) although this is not always required:

    $name = 'Codeup';
    $message = "Hello {$name}";
  • There are two types of arrays. Numerically index arrays are just like what you've used with JavaScript, although manipulating them does not use the . like in JavaScript:

    <?php
    $cohorts = ['Arches', 'Badlands', 'Carlsbad', 'Denali', 'Everglades'];
    count($cohorts); // tells you how many elements are in the array
    $cohorts[] = 'Franklin'; // adds a new element on to the end of the array
    ?>
  • Associative arrays use string for the keys. They are similar to JSON objects although the syntax is different. In creating an associative array, you use the hash rocket (=>) to assign a key to a value:

    <?php
    $student = [
        'first_name' => 'Margaret',
        'last_name'  => 'Weathers',
        'gender'     => 'F'
    ];
    
    $student['first_name']; // get the value at the key first_name
    $student['age'] = 25;   // assign 25 to the key age
    ?>
  • To iterate, or loop through, an array use the foreach statement. Again, this is similar to JavaScript arrays' forEach() but the syntax is different:

    <?php
    $cohorts = ['Arches', 'Badlands', 'Carlsbad', 'Denali', 'Everglades'];
    foreach ($cohorts as $className) {
        echo $className; // PHP assigns each individual value in the $cohorts array to $className one at a time
    }
    ?>
  • If you need to know the key or index information along with the value, you specify that in foreach with the hash rocket => again:

    <?php
    $student = [
        'first_name' => 'Margaret',
        'last_name'  => 'Weathers',
        'gender'     => 'F'
    ];
    
    foreach ($student as $key => $value) {
        echo "Student {$key} is {$value}";
    }
    ?>
  • Functions in PHP are generally similar to JavaScript, however they cannot see variables outside of themselves:

    <?php
    $aGlobalVar = 'My scope is considered GLOBAL since I am not declared inside any functions';
    
    function badFunction()
    {
        $localVar = 'My scope is LOCAL because I am being declared in a function. ';
        $localVar.= 'My scope is limited to within that function alone.';
        $aGlobalVar; // This will cause an error because $aGlobalVar is declared outside of this function
    }
    
    function betterFunction($aParameter)
    {
        // This function has a parameter declared so it can have $aGlobalVar PASSED to it
        return $aParameter . ' YAY!!!';
    }
    
    echo betterFunction($aGlobalVar);
    ?>
  • PHP will be used to control what HTML is displayed in the browser. Putting HTML in an if statement will only display the if the value evaluates to true:

    <?php $headsOrTails = rand(0, 1); // random integer from 0 to 1 (aka, either 0 or 1) ?>
    <h1>Heads or tails?</h1>
    <?php if ($headsOrTails == 0) { ?>
        <h2>Heads</h2>
    <?php } else { ?>
        <h2>Tails</h2>
    <?php } ?>
  • There is an alternative syntax for control structures that makes them easier to read when mixed with HTML. After the structure heading put colon (:) instead of opening brace ({). End the structure with endif, endfor, endwhile, endforeach, etc:

    <?php $headsOrTails = rand(0, 1); // random number from 0 to 1 (aka, either 0 or 1) ?>
    <h1>Heads or tails?</h1>
    <?php if ($headsOrTails == 0) : ?>
        <h2>Heads</h2>
    <?php else : ?>
        <h2>Tails</h2>
    <?php endif ?>
  • There is also a shorthand way to echo information with PHP. Instead of:

    <?php echo 'Hello Codeup'; ?>

    You can use the shorthand <?= /* some value */ ?>:

    <?php $cohorts = ['Arches', 'Badlands', 'Carlsbad', 'Denali', 'Everglades']; ?>
    <h1>Codeup Classes</h1>
    <ul>
        <?php foreach ($cohorts as $className) : ?>
            <li><?= $className ?></li>
        <?php endforeach ?>
    </ul>
  • PHP can be used to tie together multiple files. For building templates, the most common way to do this is using include. Simply put:

    <?php
    include 'some/file/name.php';
    ?>

    And it will be as if the contents of that file were copied and pasted directly where the include statement was.

Exercise

Using the things we've covered above, we are going to make a products catalog. Choose a particular type of media (books, movies, albums, TV shows, etc) and create a structure for it in nested PHP arrays. For example, if we were going to use albums it might look like the following:

<?php
$albums = [
    [
        'artist'   => 'Nirvana',
        'title'    => 'Nevermind',
        'released' => 1991
    ], [
        'artist'   => 'Les Savy Fav',
        'title'    => 'Let\' Stay Friends',
        'released' => 2007
    ], [
        'artist'   => 'Arcade Fire',
        'title'    => 'The Suburbs',
        'released' => 2010
    ], [
        'artist'   => 'Childish Gambino',
        'title'    => 'Camp',
        'released' => 2011
    ]
    // ...
];
?>

The important part is to make sure you have a consistent structure for each nested array. Put your data in a PHP file called items.php, make sure it is saved outside the public directory. Also outside your public directory, make a templates directory. In there you are going to create (at a minimum) header.php and footer.php. These will be the top and bottom of your page template.

In the public directory create catalog.php. This file will tie together items.php, header.php, and footer.php. It should display all the your items like a store catalog.

Bonus

If we were to create an show_item.php file to show a single item, we could create a link to it in catalog.php like the following:

<a href="/show_item.php?id=<?= $id ?>">Show Item</a>

Within show_item.php, we would need to know which individual item from the array was asked for. To find that, we would look in $_REQUEST. That variable is a builtin value to PHP. It is an associative array that takes values from either GET (values in the URL after a ?) or POST (values from a form). In our example, to find out the array index we were asked for, we would look at:

<?php
include '../items.php';
$id = $_REQUEST['id'];
$item = $items[$id];
?>

Starting with this sample code, build out a page to show a single item. Use header.php and footer.php to minimize the amount of custom template code that needs to be created for each page.

You can break your templates down into even more fine grained pieces.

You can also make a mock form for creating a new store item.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment