Summary: Understanding some topics which can be missed while learning PHP.
Switch case
If we want to compare multiple cases for each code block then we can add that case like following
$d = 3;
switch ($d) {
case 1:
case 2:
case 3:
case 4:
case 5:
echo "The weeks feels so long!";
break;
case 6:
case 0:
echo "Weekends are the best!";
break;
default:
echo "Something went wrong";
}
Alternate Syntax
We can also use alternate syntax for the while, for and each like following
$i = 1;
while ($i < 6):
echo $i;
$i++;
endwhile;
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) :
echo "$x <br>";
endforeach;
Foreach Byref
When looping through the array items, any changes done to the array item will, by default, NOT affect the original array:
By default, changing an array item will not affect the original array:
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
if ($x == "blue") $x = "pink";
}
var_dump($colors);
BUT, by using the &
character in the foreach
declaration, the array item is assigned by reference, which results in any changes done to the array item will also be done to the original array:
By assigning the array items by reference, changes will affect the original array:
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as &$x) {
if ($x == "blue") $x = "pink";
}
var_dump($colors);
PHP is a Loosely Typed Language
PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.
In PHP 7, type declarations were added. This gives us an option to specify the expected data type when declaring a function, and by adding the strict
declaration, it will throw a “Fatal Error” if the data type mismatches.
In the following example we try to send both a number and a string to the function without using strict
:
declare(strict_types=1); // strict requirement
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// Error will be raised
PHP Return Type Declarations
PHP 7 also supports Type Declarations for the return
statement. Like with the type declaration for function arguments, by enabling the strict requirement, it will throw a “Fatal Error” on a type mismatch.
To declare a type for the function return, add a colon ( :
) and the type right before the opening curly ( {
)bracket when declaring the function.
In the following example we specify the return type for the function:
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : float {
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>
PHP Array Types
In PHP, there are three types of arrays:
- Indexed arrays – Arrays with a numeric index
- Associative arrays – Arrays with named keys
- Multidimensional arrays – Arrays containing one or more arrays
Array Functions
The real strength of PHP arrays are the built-in array functions, like the count()
function for counting array items:
How many items are in the $cars
array:
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
Update Array Items in a Foreach Loop
There are different techniques to use when changing item values in a foreach
loop.
One way is to insert the &
character in the assignment to assign the item value by reference, and thereby making sure that any changes done with the array item inside the loop will be done to the original array:
Change ALL item values to “Ford”:
$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as &$x) {
$x = "Ford";
}
unset($x);
var_dump($cars);
Note: Remember to add the unset()
function after the loop.
Without the unset($x)
function, the $x
variable will remain as a reference to the last array item.
PHP – Sort Functions For Arrays
These are some of the sort functions for arrays:
sort()
– sort arrays in ascending orderrsort()
– sort arrays in descending orderasort()
– sort associative arrays in ascending order, according to the valueksort()
– sort associative arrays in ascending order, according to the keyarsort()
– sort associative arrays in descending order, according to the valuekrsort()
– sort associative arrays in descending order, according to the key
PHP Global Variables – Superglobals
Some predefined variables in PHP are “superglobals”, which means that they are always accessible, regardless of scope – and you can access them from any function, class or file without having to do anything special.
The PHP superglobal variables are:
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
Sending a request from javascript to the PHP endpoint
When sending a HTTP request in JavaScript, you can specify that the HTTP method is POST.
JavaScript function
function myfunction() {
const xhttp = new XMLHttpRequest();
xhttp.open("POST", "demo_phpfile.php");
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.send("fname=Mary");
}
}
What is a Regular Expression?
A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for.
In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers.
$exp = "/hello/i";
In the example above, /
is the delimiter, w3schools is the pattern that is being searched for, and i
is a modifier that makes the search case-insensitive.
Function | Description |
---|---|
preg_match() | Returns 1 if the pattern was found in the string and 0 if not |
preg_match_all() | Returns the number of times the pattern was found in the string, which may also be 0 |
preg_replace() | Returns a new string where matched patterns have been replaced with another string |
When to use GET?
Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.
Note: GET should NEVER be used for sending passwords or other sensitive information!
When to use POST?
Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
The PHP Date() Function
Get a Date
The required format parameter of the date() function specifies how to format the date (or time).
Here are some characters that are commonly used for dates:
- d – Represents the day of the month (01 to 31)
- m – Represents a month (01 to 12)
- Y – Represents a year (in four digits)
- l (lowercase ‘L’) – Represents the day of the week
Other characters, like”/”, “.”, or “-” can also be inserted between the characters to add additional formatting.
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
Get a Time
Here are some characters that are commonly used for times:
- H – 24-hour format of an hour (00 to 23)
- h – 12-hour format of an hour with leading zeros (01 to 12)
- i – Minutes with leading zeros (00 to 59)
- s – Seconds with leading zeros (00 to 59)
- a – Lowercase Ante meridiem and Post meridiem (am or pm)
<?php
echo "The time is " . date("h:i:sa");
?>
<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>
Session working
Most sessions set a user-key on the user’s computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans the computer for a user-key. If there is a match, it accesses that session, if not, it starts a new session.
PHP What is OOP?
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or functions that perform operations on the data, while object-oriented programming is about creating objects that contain both data and functions.
PHP – Access Modifiers
Properties and methods can have access modifiers which control where they can be accessed.
There are three access modifiers:
public
– the property or method can be accessed from everywhere. This is defaultprotected
– the property or method can be accessed within the class and by classes derived from that classprivate
– the property or method can ONLY be accessed within the class
PHP – What is Inheritance?
Inheritance in OOP = When a class derives from another class.
The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods.
An inherited class is defined by using the extends
keyword.
PHP – What are Abstract Classes and Methods?
Abstract classes and methods are when the parent class has a named method, but need its child class(es) to fill out the tasks.
An abstract class is a class that contains at least one abstract method. An abstract method is a method that is declared, but not implemented in the code.
PHP – What are Interfaces?
Interfaces allow you to specify what methods a class should implement.
Interfaces make it easy to use a variety of different classes in the same way. When one or more classes use the same interface, it is referred to as “polymorphism”.
PHP – Interfaces vs. Abstract Classes
Interface are similar to abstract classes. The difference between interfaces and abstract classes are:
- Interfaces cannot have properties, while abstract classes can
- All interface methods must be public, while abstract class methods is public or protected
- All methods in an interface are abstract, so they cannot be implemented in code and the abstract keyword is not necessary
- Classes can implement an interface while inheriting from another class at the same time
PHP – What are Traits?
PHP only supports single inheritance: a child class can inherit only from one single parent.
So, what if a class needs to inherit multiple behaviors? OOP traits solve this problem.
Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).
Leave a Reply