Kaigai Blog living abroad in my twenties

【My Study Note】PHP Codes

PHP Programming

PHP Codes

Contents

PHP

What is PHP?

There are restrictions on what we can control when using only HTML. PHP allows you to change the text that is displayed depending on the situation and audience.

How to Write PHP

<html>
    <head></head>
    <body>
        <h1>PHP</h1>
        <?php echo '<h2>Beginner</h2>'; ?>
    </body>
</html>

PHP code can be embedded within HTML. Using the special PHP tag, you can write instructions <?php … ?>. The code written in <?php … ?> will be converted into HTML and displayed.

PHP Syntax

<?php
    // This is a comment
    echo 'Hello';
    echo 'Guys!';
?>

Semicolons ; are used to separate statements in PHP. It will cause an error if there is a missing semicolon, so be careful! Also, lines that start with // are called comments and aren’t executed. Comments won’t affect your code, but they’re useful for documenting and making notes.

String Output

You can use echo to print a series of characters called a string. Put strings in single quote (‘) or double quotes (“) to print them.

Calculation

echo 7 + 3;
// output 10

Variables

Basic

<?php 
    $country = "Japan";
    echo $country;
    // Output Japan
?>

Updating Variables

<?php 
    $num = 3;
    echo $num;
    // Output 3
    $num = 8;
    echo $num;
    // Output 8
?>

Adding Numbers to Variables

Option 1

<?php 
    $num = 3;
    $num = $num + 5;
    echo $num 
    // Output: 8
?>

Option 2

<?php 
    $num = 3;
    $num += 5;
    echo $num 
    // Output: 8
?>

Option 3 (Only when you’re adding or subtracting 1)

<?php 
    $x = 3;
    $y = 3;
    echo ++$x;
    // Output: 4
    echo $y++;
    // Output: 3
?>

When you’re adding or subtracting 1, you can shorten it further with the increment operator ++ and the decrement operator –. When you put the operator before a variable, calculation gets done before echo. However, if the operator is put after a variable, the calculation is performed after echo.

String Concatenation

Option 1

<?php 
    $coffeeShop = "Starbucks";
    echo $coffeeShop."is the best"
    // Output: Starbucks is the best
    $review = "is the best";
    echo $coffeeShop.$review;
    // Output: Starbucks is the best
?>

You can concatenate strings using a period (.). This is called the dot operator in PHP.

Option 2

<?php 
    $coffeeShop = "Starbucks";
    $coffeeShop .= "is the best";
    echo $coffeeShop;
    // Output: Starbucks is the best
?>

You can omit the concatenation of a variable and a string using “.=”.

Option 3

<?php 
    $coffeeShop = "Starbucks";
    echo "{$coffeeShop} is the best";
    // Output: Starbucks is the best
    echo '{$coffeeShop} is the best';
    // Output: {$coffeeShop} is the best
?>

Within a string that is in double quotes “, you can insert a variable by putting the variable name in braces { }. This is called variable substitution. If you use single quotes ‘ instead, the variables won’t be substituted because it will be interpreted as a string even if it’s in braces.

Conditional Statement

If Statement

<?php 
    $num = 23;
    if ($num > 30) {
        echo "{$num} is greater than 30";
    } elseif ($num > 20) {
        echo "{$num} is greater than 20";
    } else {
        echo "{$num} is less than 20";
    }
    // Output: 23 is greater than 20
?>

Switch Statement

<?php 
    $singer = "Taylor Swift";
    switch ($singer) {
        case "Harry Styles":
            echo "Hello, {$singer}";
            break;
        case "Justin Bieber":
            echo "Hello, {$singer}";
            break;
        case "Taylor Swift":
            echo "Hello, {$singer}";
            break;
        default:
            echo "Error";
            break;
    }
?>

Arrays

Basic

<?php 
    $singers = array("Taylor", "Harry", "Justin");
    echo $singers[0];
    // Output: "Taylor
?>

Adding and Overwriting values

<?php 
    $singers = array("Taylor", "Harry", "Justin");
    $singers[] = "Ed";
    echo $singers[3];
    // Output: Ed
    $singers[2] = "Sekai no Owari";
    echo $singers[2];
    // Output: Sekai no Owari
?>

Associative Arrays

<?php 
    $user = array(
        // "name" is called KEYS and "Kate" is called VALUES
        "name" => "Kate",
        "age" => 23,
        "gender" => "female"
    );
    echo $user["name"];
    // Output: Kate
?>

Loops

The for Loop

<?php 
    for ($i = 0; $i <= 100; $i ++) {
        echo $i;
    }
?>
You don’t use “var” in the for loop.

The while Loop

<?php 
    $i = 1;
    while ($i <= 100) {
        echo $i;
        $i ++;
    }
?>

Break

<?php 
    for ($i = 0; $i <= 10; $i ++) {
        if ($i > 5) {
            break;
        }
        // Exits the for loop once the $i is equal to 6
        echo $i;
    }
?>

The break statement forcibly ends the current loop and is used in iterative statements like loops (for, while, foreach, etc). Break statements are generally used in combination with conditional statements like if statements.

Continue

<?php 
    for ($i = 0; $i <= 10; $i ++) {
        if ($i % 3 == 0) {
            continue;
        }
        // When $i is a multipled of 3, the current loop gets skipped
        echo $i;
    }
?>

While the break statement completely exits the loop, the continue statement only skips the current iteration but remains in the loop. The continue statement can also be used in iterative statements such as for, while, foreach, etc.

Foreach with Arrays

<?php 
    $towns = array ("Tokyo", "London", "New York");
    foreach ($towns as $town) {
        echo $town.' ';
    }
    // Output: Tokyo London New York
?>

You can retrieve values in arrays one by one as shown below. Values are sequentially assigned to the variable after the keyword as at the start of each loop. The variable name after as can be anything you want.

Foreach with Associative Arrays

<?php 
    $colors = array (
        "Apple" => "Red",
        "Banana" => "Yellow",
        "Grape" => "Purple"
    );
    foreach ($colors as $key => $value) {
        echo $key.": ".$value." ";
    }
    // Output: Apple: Red Banana: Yellow Grape: Purple
?>

In a foreach loop, array values are sequentially assigned to the key variable and value variable, then the code in the loop is repeatedly executed. An index number or a key (for associative arrays) is assigned to the key variable. However, note that the key variable is optional.

Built-in Functions

Some common and useful functions are already embedded in PHP; those are called built-in functions.

Strlen

<?php 
    $language = "PHP";
    echo strlen($language);
    // Output: 3
?>

strlen returns the number of characters in a string.

Count

<?php 
    $country = array("Japan", "US", "Australia");
    echo count($country);
    // Output: 3
?>

count returns the number of elements in an array.

Rand

<?php 
    echo rand(1, 4);
    // Returns a random number from 1 to 4
?>

rand returns a random integer between the first argument and the second argument.

Functions

<?php 
    function printCircleArea($radius) {
        echo $radius * $radius * 3.14;
    }
    printCircleArea(5);
    // Output: 78.5
?>

Return Values

<?php 
    function getSum($num1, $num2) {
        return $num1 + $num2;
    }
    $sum = getSum(1, 3);
    echo $sum; // Output: 4
?>

Return also ends the functions and methods

<?php 
function getLargerNum($num1, $num2) {
    if ($num1 > $num2) {
        echo "$num1 is greater than $num2";
        return $num1;
    }
    // If the return in the if statement is called, code down below won't be executed. 
    echo "$num2 is greater than $num1"
    return $num2;
}
?>

One thing you should remember is that “return” does not only return a value but also end functions and methods at the point where it’s called.

Creating the form

<!-- index.php -->
<form action = "sent.php" method = "post">
    <!-- Action: URL, Method: Post or Get -->
    <input type = "text" name = "name">
    <textarea name = "body"></textarea>
    <input type = "submit" value = "submit">
</form>

$_POST

<!-- sent.php -->
<?php
    echo $_POST["name"];
    echo $_POST["body"];
?>

We use $_POST to receive the value we submitted in the form. $_POST is an associative array. Therefore, we can receive the value we submitted by putting the name attribute of <input> and <textarea> in brackets [].

Object Oriented Programming

Classes and Instances

<?php 
    // Create Blueprint
    class Menu {
    }
    // Create the Instances
    $menu1 = new Menu();
    $menu2 = new Menu();
    $menu3 = new Menu();
?>

Properties and Methods

Inside a class, properties and methods of an instance (entity) are defined. A property is the data that an instance possesses, and a method is a function related to the instance.

Property

<?php 
    class Menu {
        public $name;
    }
    $curry = new Menu();
    $curry -> name = 'CURRY';
    // '$' is unnecessary for the property
    echo $curry -> name;
    // Output: CURRY
?>

Method

<?php 
    class Menu {
        // This is how to define the method
        public function hello(){
            echo "I'm an instance of Menu";
        }
    }
    $curry = new Menu;
    // This is how you can call the method
    $curry -> hello();
    // Output: I'm an instance of Menu
?>

$this

<?php 
    class Menu {
        public $name;
        public function hello() {
            echo "My name is ".$this -> name.".";
        }
    }
    $curry = new Menu;
    $curry -> name = "CURRY";
    $curry -> hello();
    // Output: My name is CURRY.
?>

When you want to access an instance property or method within a method, you can use a special variable called $this. $this can only be used within the definition of a method in the class. When a method is called, $this is replaced by an instance that is calling the method.

Getter

<?php
class Review{
  private $menuName;
  private $body; 
  public function __construct($menuName, $body) {
    $this->menuName = $menuName;
    $this->body = $body;
  }
  public function getMenuName() {
    return $this->menuName;
  }
  // So you can get this $menuName from outside the class with using like this: "echo $menu->getName()";
}
?>

Constructors

<?php 
    class Menu {
        public function __construct(){
            echo "A menu was created";
        }
    }
    $curry = new Menu;
    // Output: A menu was created
?>

If you define a special method named __construct(), this method will be called automatically when you create an instance using new. This kind of method that is called when a new instance is created is called a constructor.

You can pass the arguments with using constructor

<?php 
    class Menu {
        public $name;
        public function __construct($name){
            $this -> name = $name;
        }
    }
    $curry = new Menu ("CURRY");
    echo $curry -> name;
    // Output: CURRY
?>

Class Property

<?php class Menu {
    public static $count = 4;
    // Adding Static makes this a class property
}
echo "Item count: ".Menu::$count;
// Output: Item count: 4
?>

While the data of each instance is called a property, the data of each class is called a class property; more commonly known as a static property. We define class properties using static. We access a class property using double colon(::) as follows: className::$classPropertyName. Let’s make sure to put $ directly after ::.

Self

<?php class Menu {
    public static $count = 4;
    public function __construct(){
        self::$count++;
        // Every time the new instance is created, one would be added to the $count
    }
}
?>

When accessing a class property from within a class, we use a special variable called self. When used in a class, self refers to the class itself. We use self as follows: self::$classPropertyName.

Make class property to be private as well

<?php class Menu {
    private static $count = 4;
    public function __construct(){
        self::$count ++;
    }
    public static function getCount(){
        return self::$count;
    }
}
echo Menu::getCount();
?>

Protected Properties

<?php 
    class Drink extends Food{
        public function __construct($name, ...) {
            $this->name = $name;
            // Error: You cannot access the "name" property
        }
    }
?>

In order to access a property defined in the parent class from the child class, we need to set the access right of the property to protected. A property whose access is protected can only be accessed from its own class and from child classes which inherit that class.

<?php 
    class Menu {
        protected $name;
    }
    class Drink extends Food{
        public function __construct($name, ...) {
            $this->name = $name;
            // You can access!!
        }
    }
?>

Parent

<?php 
    class Drink extends Food{
        public function __construct($name, $price, $image, $type) {
            parent::__construct($name, $price, $image);
            $this->type = $type;
        }
    }
?>

To call a method defined in the parent class when overriding, we use parent as follows: parent::methodName. The method of the parent class is executed at the place where parent::methodName is described. By doing this, we can write the constructor we created earlier in a clear manner.

Query Strings

Query Strings

<a href="showphp?name = <?php echo $curry->getName() ?>">
  Click Here
</a>
// Key: name, Value: <?php echo $curry->getName() ?> (Which is CURRY)

It’s possible to put in simple information by typing “key=value” after the “?” at the end of the URL. This is called a query string, and using this enables us to give information to the link destination.

You can use this such as when you want to tell which button was clicked

$_GET

<?php 
    echo $_GET["name"]; 
    // Output: Curry 
?>

In order to receive query strings, “$_GET” is used. The query string is included inside “$_GET” as an associative array. This means that a value can be taken out using “$_GET[‘key’]”.

Others

You can omit the semi-colons

<p><?php echo $curry->name ?></p>
<!-- You can omit the semi-colon ":" -->

You need to close the statement by placing a semi-colon ; at the end. But, when the code is a single statement there isn’t a need to close the statement. In these cases, you can omit the semi-colon.

Embedding foreach Loops in HTML

  • Use “:” instead of “{“.
  • Use “endforeach” instead of “}”.
<?php 
$words = array('apple', 'banana', 'orange');
?>
<?php foreach($words as $word):?>
    <!-- You type endforeach instead of "{" -->
    <p><?php echo $word ?></p>
<?php endforeach ?>
<!-- You type endforeach instead of "}" -->

As with the foreach loop, the if, for,while and switch sequences can be closed with endif, endfor, endwhile and endswitch respectively.

Require once

<?php require_once('data.php') ?>

To use the other PHP files, you can use require_once to import them.

Encapsulation

<?php class Menu {
    private $name;
    public function __construct ($name){
        $this -> name = $name;
    }
}
$curry = new Menu ("CURRY");
echo $curry -> name;
// This would be error. You cannot access the "private" from outside the class
?>

Encapsulation is the act of restricting access to class properties and methods. public is used to allow access from outside the class, and private is used to limit that access. In general, class properties are made private.

How to access the private?

<?php class Menu {
    private $name;
    public function __construct ($name){
        $this -> name = $name;
    }
    public function getName(){
        return $this->name;
    }
}
$curry = new Menu ("CURRY");
echo $curry -> getName();
// Output: CURRY
?>

Setter

<?php class Menu {
    private $orderCount = 0;
    public function setOrderCount($orderCount) {
        $this->orderCount = $orderCount
    }
}
$curry = new Menu ("CURRY");
$curry->setOrderCount(3);
// Set the value using the setter
echo $curry->getOrderCount();
// Output: 3
$curry->orderCount = 4;
// ERROR: It can't access because it's private.
?>

When you make the access to a property private, you can’t change the value of the property from outside the class. Here, we will define a method that will change the property value. This kind of method which exists only to change the value of a property is known as a setter. Setters are commonly named like setPropertyName().

Inheritance Syntax

<?php class Drink extends Menu {
    // Inherits the Menu Class
}
?>

Instance Of

<?php 
    $coffee = new Drink();
    if ($coffee instanceof Drink) {
        // True (You can find out if $coffee instance belongs to Drink class or not)
        echo $coffee->getName()."is an instance of the Drink class";
    } 
    if ($coffee instanceof Food) {
        // False
        echo $coffee->getName()."is an instance of the Food class";
    }
?>

Using instanceof, we can determine whether an instance belongs to a particular class. By writing $instanceName instanceof className, the code will return true if the instance belongs to the specified class, and false otherwise.

Strlen

<?php
echo strlen("Hello");
?>

The strlen() function returns the length of a string.

Strrev

<?php
echo strrev("Hello World!");
?>
// Output: !dlroW olleH

The strrev() function reverses a string.

Str_replace

<?php
echo str_replace("world","Peter","Hello world!");
?>
// Replacing the characters "world" in the string "Hello world!" with "Peter":

The str_replace() function replaces some characters with some other characters in a string.