WBDV243

Web Authoring II

PHP

Basics

PHP - Essentials

  • pages must be stored on a server
  • use the filename extension .php
  • enclose PHP code in PHP tags
    • Opening tag: <?php
    • Closing tag: ?>

Common Features

  • variables - placeholders for values
  • arrays - hold multiple values
  • conditional statements - make decisions
  • loops - repetitive tasks
  • functions/objects - preset tasks

Variables

Placeholders for values that we don't know, or that may change.


<?php
  $my_var;
?>
  • always begin with $
  • first character after $ can not be a number
  • no spaces/punctuation except the underscore _
  • variable names are case sensitive

Best Practices

  • choose meaningful names
  • use camelCase or under_score for multiple words

Examples


<?php
  // string
  $first_name = "Phil";

  // number
  $total = 99;

  // numbers can include decimals, no commas
  $total = 99.15
?>

<body>
<?php
  $first_name = "Phil";
?>
...
browser window
My name is…

<body>
<?php
  $first_name = "Phil";

  echo $first_name;
?>
...
browser window
My name is…

Echo vs Print


<body>
<?php
  $first_name = "Phil";

  echo $first_name;
  print $first_name;
?>


<body>
<?php
  $first_name = "Phil";
  $total      = 99;

  print $first_name;
  echo '
'; echo $first_name, $total; ?>
browser window

Comments


// Single line comment

# Single line comment

/*
Multiple lines in this comment.
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Possimus, assumenda, rem excepturi perferendis dicta vel pariatur!
*/

Whitespace


$school = 'Drexel';
$mascot = 'Dragons';

echo $school . ' ' . $mascot;

echo 'My favorite college team is the ' . $school . ' ' . $mascot;

Arithmetic

+ - * /


$my_number = 5;
echo $my_number + 2; // 7

Increment


$number = 5;
$result = ++$number * 2; // 12

echo 'number = ' . $number . ' | ' . 'result = ' . $result;

// output: number = 6 | result = 12

$number = 5;
$result = $number++ * 2; // 10

echo 'number = ' . $number . ' | ' . 'result = ' . $result;

// output: number = 6 | result = 10

Arrays

Lists of values


<?php
// The old way
$characters = array('one','two','three');

// The new way
$characters = ['Bugs','Daffy','Speedy'];

Accessing Arrays


<?php
$characters = ['Bugs','Daffy','Speedy'];

print_r($characters);

// output: Array ( [0] => Bugs [1] => Daffy [2] => Speedy )

Accessing Arrays


<?php
$characters = ['Bugs','Daffy','Speedy'];

echo $characters[0]; // Bugs