PHP Notes
PHP Notes
Comments:
//single line
# single line
/* multi-line*/
Variables:
Use the $ sign to declare a variable
Ex: $name = “Name”;
$age = 28;
Dynamic variable:
$a = “hello”;
$test=”a”;
echo $$test; (echoing $test will give you ‘a’ as output)
Type casting can also be used to change the type of a variable. But type
casting produces a copy of the variable and has to be stored in a new
variable whereas settype modifies the data type of the original variable
Type casting: just use the data type before the value Variable =
(data_type) variable / value;
To know all the details of a variable (type, size, what it stores) use,
var_dump($variable, $variable, ..) (without echo)
Use is_string(variable) to check if a variable contains a string or not
(without echo, returns true or false)
Similarly,
is_int()
is_bool()
is_double()
is_float()
constants:
define(‘PI’, 3.14); (then we can just print it (echo PI;))
php built-in constants:
SORT_ASC (value = 4)
PHP_INT_MAX (value = 922337…)
Arithmetic operations:
$a + $b
$a - $b
$a * $b
$a / $b
$a % $b
Comparison operators: <, >, <=, >=, ==, ===, != or <>, !==
Ternery operator: (condition)?value:value;
Logical operators: &&, ||, !
Number functions:
abs()
pow(value, power)
sqrt()
max(value, value,..)
min(value, value,..)
round()
floor()
ceil()
number formatting:
use number_format(variable, digits_after_decimal,
“decimal_separator”,”thousand separator”);
Strings:
Strings can be written in both single quotes and double quotes
Advantage of using double quotes: variables can be included in the
string (you don’t have to concatenate)
In single quotes, the variable has to concatenated.
String functions:
strlen($variable/ string)
trim() //removes white-spaces
ltrim()
rtrim()
str_word_count() //gives the number of words
strrev()
strtoupper()
strtolower()
ucfirst() //convert the first letter to upper case
lcfirst()
ucwords() //similar to capitalize
strpos(string, string_to_be_searched) //searches
string_to_be_searched in string and returns the first index of the
string_to_be_searched, else, returns an empty space. It is case
sensitive
stripos() //ignores case, similar to strpos()
substr(string, from_position, length_of_substring)
str_replace(string_to_be_replaced, string_to_replace, string in
which the replace is to take place) //case sensitive
str_ireplace() //ignores case, similar to str_replace()
If using HTML tags in a variable and then using echo, those tags will be
interpreted as HTML tags.
Ex: $string = “<b>Hello</b>”; echo $string; output: Hello
Arrays:
$fruits=[“Banana”,”Apple”,”Orange”];
$fruits=new array(“Banana”,”Apple”,”Orange”);
Arrays can contain elements of multiple data types
Add element:
array_push($fruits, element);
Sorting array:
sort($fruits); //sorts in ascending order
rsort($fruits); //sorts in reverse order
Associative array:
Consists of key-value pairs
$person=[
“name”=>”Bob”,
“age”=>”19”;
];
Shorthand:
$person[“address”] = $person[“address”] ?? ”unknown”;
two-dimensional arrays:
$todos = [
[‘title’ => ‘todo title 1’, ‘completed’ => true],
[‘title’ => ‘todo title 2’, ‘completed’ => false]
];
Conditional statements:
If(condition){
}
Single statements can be written on the same line,
If(condition) statement;
== is comparison operator
=== is also comparison operator, but it compares data types instead of
values (20==”20” will give true while 20===”20” will return false)
If(){
}
elseif(){
}
else{
}
Ternary if:
if $age<22 ?? “Yound”:”Old”;
Switch statement:
$user = ‘a’;
switch($user){
case ‘b’:
statements;
break;
case ‘c’:
statements;
break;
default:
statements;
}
Loops:
while(condition){
}
do{
}while(condition);
for($i=0;i<10;$i++)
{
}
Functions:
function hello()
{
Statements;
}
hello();
function($hello)
{
}
function sum(…$nums){
}
This basically takes in the parameters, and stores them in an array
called nums.
Arrow function:
fn(arguments) => expression;
its similar to java, has no name (anonymous) and executes one
statement.
Dates:
Print current date: date(‘Y-m-d H:i:s’); //output: 2020-10-12 09:57:20
Print yesterday: date(‘Y-m-d H:i:s, time() – 60*60*24) //time() returns
current time in seconds
Date in another format: date(‘F j Y H:i:s’) //output: October 12 2020,
09:57:20
Functions in PHP:
Ex:
function processMarks($marksArr){
$sum=0;
foreach($marksArr as $value){
$sum+=$value;}
return $sum;}
$bob = [99,99,99];
$sumBobMarks = processMarks($bob); //it will store 297 (out of 300)
Scope of a function:
static: if you want a local variable not be deleted after the function
is executed, you can declare it as static.
Global:
<?php
function sum()
{
Static $ans=1;
echo $ans. “<br>”;
$ans++;
}
Sum();
Sum();
?>
Output is 1
Output is 2
Static variable is also local to a function. But it doesn’t lose its value after the
execution over, and can’t be referenced in other functions.
Files:
If there is repeated HTML code, then write it in a separate .php file and
store it in a folder called partials. Then, where ever needed, include the
file using:
<?php include “partials/filename.php”; ?> //theres also include_once
To include files that are absolutely necessary, use require / require_once
Another reason to use files: if one file contains functions, for example 2
functions one to add two numbers called function add($a, $b) with 2
parameters that returns the sum and a subtract($a, $b) that returns the
difference. If we include this file in another php file, we can then use
those functions (call them like add(4,5);, subtract(5,4);)
Constructor:
class Person{
public $name;
public $surname;
private $age;
class Person{
public $name;
public $surname;
private $age;
public static $counter = 0;