IF ELSE Statements
- Examples of if else syntax
// what will be printed?
$var = true;
if($var){
echo "var is true!";
}else{
echo "var is false!";
}
- “” is false
- Empty array is false
- 0 is false
// what will be printed?
$var = "";
if($var){
echo "var is true!";
}else{
echo "var is false!";
}
Arrays in PHP
$arr = array("1", "2", "3"); // create an array
echo $arr[1]; // what will be printed?
$arr = ["1", "2", "3"]; // this is the same
echo $arr[1]; // the same!
- In the above we created a simple array.
- Remember: an array starts in index 0.
- Therefore printing the index 1 of the array printed the second element.
$arr = ["1", "2", "3"];
echo $arr[1]; // prints 2
- In PHP we can create arrays with keys. It’s very useful
$arr = ["key1" => "value1", "key2" => "value2"];
echo $arr['key1'];
Loops in PHP
For Loop…..
- Notice the 3 components from left to right: starting the counter, checking some condition, increment the counter.
- Notice the new line character \n
for ($x = 1; $x <= 10; $x++) {
echo $x . "\n"; // prints 1 2 3 4 … 10 in separate lines
}
For Each Loop…
// for regular array
$arr = ["1", "2", "3"];
foreach($arr as $element){
echo $element . "\n"; // prints 1 2 3 in separate lines
}
// for array with keys
$arr = ["key1" => "value1", "key2" => "value2"];
foreach($arr as $element){
echo $element . "\n"; // prints value1, value2 in separate lines
}
- On array by key and value.
$arr = ["key1" => "value1", "key2" => "value2"];
foreach($arr as $key => $element){
echo $key . " " . $element . "\n"; // prints key1 value1, key value2 in seperate lines
}
Live Coding
- Iterate over an array of strings and print all strings which are longer then 6 characters in a new line.
- Now print only if they are longer then 6 and shorter then 10.