// Declaring and initializing variables (no need to specify a data type!)
$x = 5;
$xspeed = 4.23;
$x = $x + $xspeed;
echo $x;
$name = "Zoog";
$title = "Cosmonaut";
echo $title . " " . $name;
echo "
";
// Basic conditional in PHP
if ($x > 5) {
$x = rand(0,10);
echo $x . " is greater than 5";
} else {
echo $x . " is less than or equal to 5";
}
echo "
";
// Loop in PHP
for ($i = 0; $i < 10; $i++) {
echo $i;
}
echo "
";
// Arrays in PHP
// Creating an array
$nameList = array("Joe","Jane","Bob","Sue");
echo $nameList[2];
// Adding an element to the end of that array
$nameList[] = "Zoog";
echo $nameList[4];
echo "
";
// Create an array with a loop
for ($i = 0; $i < 10; $i++) {
$nums[$i] = rand(0,10);
}
// Using foreach syntax
foreach ($nums as $value) {
echo $value . " " ;
}
// Getting the size of an array
echo "
The size of the array is " . sizeof($nums);
// An associative array
$studentIDs["Joe"] = 23;
$studentIDs["Jane"] = 41;
// Calling a function
printDate();
// Creating an object
$frank = new Human("Frank");
// Calling a function on the object
$frank->show();
?>
// Defining a function
function printDate() {
echo "The Date and Time is: ";
$today = date(DATE_RFC822);
echo $today;
}
?>
// Defining a class
class Human {
// Declaring instance variables
public $firstname = "default";
public $height = 0;
// Writing a constructor
function __construct($n) {
// Notice the use of $this->varname
$this->firstname = $n;
$this->height = rand(5,6);
}
// A function
function show() {
echo "
" . $this->firstname . " is " . $this->height . " feet tall.";
}
}
?>