Peng Zhang

Peng Zhang

Developer

© 2021

Dark Mode

PHP Intro

  • Basics: Output & Data Type
  • Control Structure
  • Math
  • Loops
  • Functions and Objects

PHP Intro

<?php
//Single line comment
echo 'Hello World';  // Ouputs Hello World
?>

<!--not recommended-->
<?= 'Hello World' ?>

<?php
/*
 * multi-line comments
 */
print 'Hello World';
// The difference between echo and print
// echo has no return value, while pirnt has a return value of 1 so it can be used in expressions
// echo can take multiple parameters which print can take one argument
// echo is marginally faster than print
?>

<!-- Data Type -->
<?php
//variable
$age = 34;

//constants
define('VERSION', 1.1); //PHP 8
const CONSTANT = 'Hello World'; //PHP 5.6
//VERSION = 1.2; //will not work
//define('VERSION', 1.2); //Also will not work
//
//
//variable types
//Integers
//Floats
//Characters
$first_letter = 'J';
$second_letter = "J";
//Strings
$letters = "Joe";
//Booleans
//Arrays
//Double Quotes VS Single Quotes
// Strings in double quotes wil be processed by PHP before being outputted.
// Use Single Quotes first which is fast
$name = "Joe";
echo "Hello, $name"; //output: Hello, Joe

echo 'Hello, $name'; //output: Hello, $name
//concatenation operator .
echo 'Hello, ' . $name . '!'; //ouput: Hello, Joe! 
//escape character
echo "Welcome to Joe\'s Website.";

echo "This is line 1.\n";
echo "This is line 2.";

echo '<br/>';
echo 'Joe\'s Nickname in HS was "Joey Calzone"';
echo "Joe's Nickname in HS was \"Joey Calzones\"";

echo '<br/>';
?>


<!-- Arrays -->
<?php
//Arrays
//Can contain mix data types
//Indexable Array
$colors = array('red', 'blue', 'green');
print_r($colors);
echo '<p>' . $colors[1] . '</p>';

//Add a new value
$colors[] = 'yellow';

//Associatvie Array
//Numbered index to String
$homeTown = array(
    'Joe' => 'Middletow, NY',
    'Erin' => 'West Chester, PA',
    'Dave' => 'Exton, PA',
    'Brian' => 'Grand Rapids, MI',
);
echo '<pre>';
print_r($homeTown);
echo '</pre>';

echo '<p>' . $homeTown['Dave'] . '</p>';

//Multidimensional Arrays
//An array of Arrays
$brothers = array(
    'Joe' => array('age' => 34, 'job' => 'teacher', 'state' => 'PA'),
    'Phil' => array('age' => 33, 'job' => 'photographer', 'state' => 'NY'),
    'Mike' => array('age' => 32, 'job' => 'logistics', 'state' => 'NY'),
    'Rob' => array('age' => 29, 'job' => 'manager', 'state' => 'FL'),
);

echo '<pre>';
print_r($brothers);
echo '</pre>';
echo '<p>' . $brothers['Rob']['state'] . '</p>';
?>

<!-- Comparison Operator-->
<?php
//Compare equality with ==
// PHP 7
var_dump(0 == 'foo'); //True
//
// PHP 8
// When comparing to a numeric string, use a number comparison
// Otherwise, convert the number to string and use a string comparison
var_dump(0 == 'foo'); //False

var_dump('1' == 1);

//Identical Comparison with ===
var_dump(1 === 1);
var_dump('1' === 1);

// Spaceship Operator <=>
// The spaceship operator is used for comparing two expressions. 
// It returns -1, 0 or 1 when $a is respectively less than, equal to, or greater than $b.
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
?>

<!-- Logic Operator -->
<?php
$a = 9 > 5; // true
$b = 10 != 10;  // false
$c = $a && $b;  // false
$d = $a || $b;  // true
$e = $b && $c;  //false
$f = $a || $d;  //true

$logic = array($a, $b, $c, $d, $e, $f);

echo '<pre>';
var_dump($logic);
echo'</pre>';

$c = $a and $b; // true
// c is assigned to a; b is being evaluated
?>

<!-- Control Structures -->
<?php
// if statements
$a = 10;
$b = 3;
if ($a > $b) {
    echo "$a is greater then $b";
} else if ($b > $a) {
    echo "$b is greator then $a";
} else {
    echo "$a and $b appear to be equal";
}


//Alternative Syntax
if ($a > $b):
    echo "$a is greater then $b";
elseif ($b > $a) :
    echo "$b is greator then $a";
else:
    echo "$a and $b appear to be equal";
endif;
?>

<!-- Alternative Conditional Syntax Example -->
<?php if ($home_page) : ?>
    <header>
        <h1>Welcome to the home page of my website!</h1>
        <p>Have a look around.</p>
    </header>
<?php endif; ?>


<!--Yoda Conditionals-->
<!-- Good, warn when missing a equal mark and avoid the assignment expression ($i=10) is evaluated to true -->
<?php
if (10 == $i) { /* do somehing */
}
?>

<!-- Bad -->
<?php
if ($i == 10) {
    /* do somehing */
}
?>

<!-- Ternary operation -->
<?php
$message = $is_logged_in ? 'Welcome back!' : 'Hello There';

$name = isset($name) ? $name : 'Joe';

$name = null;
// Elvis Operator
$name = $name ?: 'Joe'; // work when $name is null
?>

<!-- Switch Statements -->
<?php
$total = 10;
switch ($total) {
    case 1:
        echo '<p>$total is 1</p>';
        break;
    case 2:
        echo '<p>$total is 2</p>';
        break;
    default:
        echo '<p>$total is more than 2</p>';
}


// Alternative Syntax
switch ($total) :
    case 1:
        echo '<p>$total is 1</p>';
        break;
    case 2:
        echo '<p>$total is 2</p>';
        break;
    default:
        break;
endswitch;
?>

<!-- Match Expression-->
<!-- PHP8 
-- Compare values strictly (===) instead of loosely (==) as the switch statement does
-- A match expression returns a value
-- Do not fall-through to later cases the way switch statements do
-- A match expression must be exhaustive
-->
<?php

function add_to_x($x) {
    return $x + 5;
}

$x = 0;

$result = match ($x) {
    -2, -1, 0 => add_to_x($x),
    1 => '$x is 1',
    2 => '$x is 2',
    default => '$x is neither 1 nor 2',
};

$result2 = match (true) {
    $x <= 0 => '$x is not positive',
    $x == 1 => '$x is 1',
    $x == 2 => '$x is 2',
    default => '$x is neither 1 nor 2',
};

echo $result;
echo $result2;
?>


<!-- Math -->
<?php
//Arithmetic Operators
// Addition +
// Subtraction -
// Multiplication *
// Division /
$a = 2;
echo $a + 2;

$b = 3;
echo $b - $a;

$c = $a * $b;
echo $c;

echo $c / $a;

//Negate value
$num = 20;
echo -$num;

// Exponent
echo 5 ** 2; // 25
//Modulus(%)
$a = 2;
$b = 3;
echo $b % $a; // 1
echo 15 % 9; // 6

if ($a % 2 == 0) {
    echo "<p>$a is evne.</p>";
} else {
    echo "<p>$a is odd.</p>";
}

// Incrementing and Decrementing
// pre-
$a = 5;
// this will be 6
echo 'The value of $a is ' . ++$a . '<br/>';
// this will be 6
echo 'Now $a is ' . $a . '<br/>';

// post-
$a = 5;
// this will be 5
echo 'The value of $a is ' . $a++ . '<br/>';
// this will be 6
echo 'Now $a is ' . $a . '<br/>';

$a = 'A';
echo '$a is ' . ++$a . '<br/>'; // $a is B

$a = 1;
$a += 5; // 6
$a /= 5; // 0.2
?>


<!-- Loop -->
<?php
//while
$i = 0;
do {
    echo "<p>$i</p>";
    $i++;
} while ($i < 10);

while ($i < 10) {
    echo "<p>$i</p>";
    $i++;
}

//for
for ($i = 0; $i < 10; $i++) {
    echo "<p>$i</p>";
}

$colors = ['red', 'blue', 'green', 'yellow']; //PHP8 New Array Creation Syntax

for ($i = 0; $i < sizeof($colors); $i++) {
    echo '<p>' . $colors[$i] . '</p>';
}

//foreach
foreach ($colors as $color) {
    echo "<p>$color</p>";
}

$home_town = ['Joe' => 'Middletow, NY',
    'Erin' => 'West Chester, PA',
    'Dave' => 'Exton, PA',
    'Brian' => 'Grand Rapids, MI',
];
;

foreach ($home_town as $name => $town) {
    echo "<p>$name lives in $town</p>";
}
?>


<!-- Functions and Objects -->
<?php

function hello_world() {
    echo 'Hello World';
}

function print_hello_world() {
    return 'Hello World';
}

echo '<p>' . print_hello_world() . '</p>';

function is_bigger($a, $b) {
    return $a >= $b;
}

$bigger = is_bigger(10, 5);
?>

<p><?php hello_world() ?></p>

<?php
// built-in functions
echo date('F d,y'); //curent date: September 13, 21

// custom functions
function is_palindrome($string) {
    // convert string to lowercase and remove spaces
    $string = str_replace(' ', '', strtolower($string));

    // check string against the same string reversed
    return $string == strrev($string);
}

$check_string = 'wow';
if (is_palindrome($check_string)) {
    echo "<p>$check_sting is a palindrome</p>";
}

// union typing variable
// only accept integer arguments
function double_int(int $a) {
    return $a * 2;
}

function double(int|float|null $a) {
    return $a * 2;
}

echo double(3); // 6
echo double(3.4); //6.8
echo double(true); //2

// Optional or named arguments
function multiplier($a, $multiplier = 2) {
    return $a * $multiplier;
}

echo multiplier(4); // 8
echo multiplier(4, 4); // 16

function math($a, $b = 2, $op = 'multiply') {
    if ('add' == $op) {
        return $a + $b;
    } else if ('sub' == $op) {
        return $a - $b;
    } else if ('divide' == $op) {
        return $a / $b;
    }

    return $a * $b;
}

echo math(4); //8
echo math(4, 3); // 12
echo math(4, 3, 'add'); // 7
echo math(4, op: 'add'); // 6
echo math(4, op: 'add', b: 12); //16

// class
class Person {

//    in PHP 8, we do not need to define thses properties here
//    var $name;
//    var $age;
//    var $birthday = false;
    // constructor
    function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }

    public function get_name() {
        return $this->name;
    }

    public function get_age() {
        return $this->age;
    }

    public function set_name($new_name) {
        $this->name = $new_name;
    }

    public function set_birthday($b) {
        $this->birthday = $b;
        $this->update_age();
    }

    private function update_age() {
        $this->age = ($this->birthday) ? ++$this->age : $this->age;
    }

}

$joe = new Person('Joe', 35);
$rob = new Person('Rob', 30);

echo $joe->get_name() . '<br/>';
echo $rob->get_name() . '<br/>';

$joe->set_birthday(true);
echo $joe->get_age();
?>