PHP: Expressions

Derek Bridge

Department of Computer Science,
University College Cork

PHP: Expressions

Aims:

Writing strings using double quotes

echo "\"Marry me,\" he said.\n\"No way,\" she replied.";
echo "\"In that case, 1\\2 a pound of cheese, please," he said.";

Interpolation

Interpolation continued

Arithmetic expressions

<?php
 $quantity = 1000;
 $pricePerBanana = 0.14;
 $discountPerCent = 25;

 $fullPrice = $quantity * $pricePerBanana;
 $discount = $fullPrice * $discountPerCent / 100;
 $actualPrice = $fullPrice - $discount;

 echo "<table>";
 echo "<tr><th>Full price:</th><td>{$fullPrice}</td></tr>";
 echo "<tr><th>Less discount:</th><td>{$discount}</td></tr>";
 echo "<tr><th>Actual price:</th><td>{$actualPrice}</td></tr>";
 echo "</table>";
?>

Arithmetic expressions

Arithmetic expressions

String expressions

String expressions

Class exercise: What is the output from the following?

$message = 'Ha';
echo $message . $message;
echo $message . $message . $message . 'Ho' . 'Ho' . 'Ho';
$message .= 'ppy';
echo $message . ' Xmas';
$age = 6;
echo $message . ' ' . $age . 'th Birthday';

PHP's 100+ built-in functions for strings

Class exercise