Lesson-04-PHP-echo-print-and-Control-Structures
Lesson-04-PHP-echo-print-and-Control-Structures
ADVANCED WEB
PROGRAMMING
Unit 5:
PHP: echo/ print, and
Control Structures
What is echo & print statements in
PHP?
Output:
Output:
Hello, World!
7 + 3 = 10
.
Output:
Hello, world!
Displaying Variables: Displaying
variables with print statements is also the
same as that of echo statements.
<?php
// Defining the variables
$text = "Hello, World!";
$num1 = 7;
$num2 = 3;
Output:
Hello, World!
7 + 3 = 10
Difference between echo and print statements in
PHP
• The If statement
The if statement executes a piece of
code if a condition is true.
if (condition) {
// code to be executed in case the
condition is true
}
Example would be:
<?php
$age = 13;
<?php
$age = 27;
<?php
for ($i=0; $i < 5; $i++) {
echo "This is loop number $i
";
}
?>
• The while loop
<?php
$i=0; // initialization
while ($i < 5) {
echo "This is loop number $i
";
$i++; // step
}
?>
• The do…while loop
<?php
$i = 0; // initialization
do {
$i++; // step
echo "This is loop number $i
";
}
while ($i < 5); // condition?>
• The foreach loop
<?php
$var = array('a’, 'b’, 'c’, 'd’, 'e'); // array declaration
<?php
$languages = array("JS”, "PHP”, “SQL”, “C#”);
?>
Array elements are accessed like
this: $arrayName [positionIndex]. For the
above example we could access “PHP”
this way: $languages[1]. Position index is
1 because in programming languages the
first element is always element 0. So, PHP
would be 1 in this case.
Three types of arrays in PHP
• Indexed Arrays
<?php
$names = array(“Gon", “Luffy", “Killua");
?>
<?php
// this is a rather manual way of doing it
$names[0] = “Gono";
$names[1] = “Luffy";
$names[2] = “Killua";
?>
Example would be:
<?php
$names = array(“Gon", “Luffy", “Killua");
echo "My friends are " . $names[0] . ", " . $names[1] . " and " . $names[2];
?>
Looping through an indexed array is
done like
<?php
$names = array(“Gon", “Luffy", “Killua");
$arrayLength = count($names);
<?php
// this is a rather manual way of doing it
$namesAge[‘Gon'] = “12";
$namesAge[‘Luffy'] = "14";
$namesAge[‘Killua'] = “13";
?>
Example would be:
<?php
$namesAge = array(“Gon"=>“12", “Luffy"=>"14", “Killua"=>“13");
echo “Gon's age is " . $namesAge[‘Gon'] . " years old.";
?>
Looping through an associative
array is done like
<?php
$namesAge = array(“Gon"=>“12", “Luffy"=>"14", “Killua"=>“14");