Final PHP Examples
Created Friday 21 April 2017
If:
<?php
$value = 14;
if ($value < 12 )
{
echo "the value is LESS than 12";
}
else
{
echo "it's MORE than 12";
}
echo "<br>and we're done";
Another if:
<?php
//Notice the lack of { } for one-line blocks of if/else code.
$age = 6;
$playground_min_age = 5;
$playground_max_age = 12;
if ($age < $playground_min_age)
echo "You are too young to play on the playground. Go away!";
elseif ($age > $playground_max_age)
echo "You are too old to play on the playground. Weirdo.";
else
echo "You can come play on the playground";
?
for:
<?php
$count = 15;
for ($i = 0; $i < $count; $i++)
{
echo "<li>FOR STYLE! We are on $i in this loop!</li>";
}
?>
Arrays:
<?php
// This creates the array AND puts values in simultaneously
$myColors = array("red","green","blue");
// Adds element:
$myColors[] = "yellow";
// Arrays are indexed at zero
echo "The thing indexed at 0 is $myColors[0] <br>";
echo "Lets try this: <br>";
foreach ( $myColors as $eachcolor ) {
echo "<p style=\"color:$eachcolor;\"> I like this color </p>";
echo "\n";
}
Array Functions
<?php
//Let us first setup some simple arrays:
$bad_ac_dorms = array("Dorman", "Smith", "McCollum", "Rogers", "Kellum", "Reynolds");
$cruddy_dorms = array("Smith", "Kellum", "Reynolds", "Landis", "Degraff", "Cawthon");
//Try to keep your variable names shorter than this...
$dorms_both_cruddy_and_with_bad_ac = array_intersect($bad_ac_dorms, $cruddy_dorms);
//Note the lazy way to print an array below
echo "The following dorms are cruddy and have bad ac:";
print_r($dorms_both_cruddy_and_with_bad_ac);
echo "<br>";
Associative Arrays
<?php
//My associative array
$marvel = array ( "Iron Man" => "Earth",
"Thor" => "Asgard",
"Hulk" => "Earth",
"Loki" => "Asgard",
"Captain America" => "Earth",
"Hawkeye" => "Earth");
// echo "Iron Man is from " . $marvel["Iron Man"];
echo "<br>";
foreach($marvel as $character => $homeplace)
{
if ($homeplace == "Earth"){
echo "$character is human <br>";
}
elseif ($homeplace == "Asgard"){
echo "$character is alien or something<br>";
}
else {
echo "I DONT EVEN KNOW WHATS GOING ON"; // IF WE SEE THIS SOMETHING IS VERY VERY WRONG.
}
}
?>
Nested arrays
<?php
$ships = array();
$ships["Nebuchadnezzar"] = array("Captain" => "Morpheus" , "First Mate" => "Trinity");
$ships["Logos"] = array("Captain" => "Niobe", "First Mate" => "Ghost");
$ships["Osiris"] = array("Captain" => "Thadeus" , "First Mate" => "Jue");
$ships["Caduceus"] = array("Captain" => "Ballard" , "First Mate" => "Malachi");
//Let us print a HTML table out of this:
echo "<table>";
echo "<tr>";
echo "<th>Ship name</th>";
echo "<th>Captain</th>";
echo "<th>First Mate</th>";
echo "</tr>";
foreach($ships as $currShip => $currShipAtts)
{
echo "<tr>";
echo "<td>$currShip</td>";
echo "<td> {$currShipAtts["Captain"]} </td>";
echo "<td> {$currShipAtts["First Mate"]} </td>";
echo "</tr>";
}
echo "</table>";
Backlinks: FSU Courses:LIS5364