You are on page 1of 22

PHP

 PHP – Hypertext Preprocessor


 One source general-purpose scripting language
 Server-side language

All php is written inside the <?php ?> tag


To print something on the screen, use echo “what to print”;
NOTE: if we use single quotes with echo, the variable names will be
printed whereas if we use double quotes, the variable value will be
printed
We can also print HTML tags

Comments:
//single line
# single line
/* multi-line*/

Variables:
Use the $ sign to declare a variable
Ex: $name = “Name”;
$age = 28;

To print the variable, use echo $name;


To concatenate, use “.” (dot)
Ex: echo $name.”<br”>; (this will print the name along with a space)

Dynamic variable:
$a = “hello”;
$test=”a”;
echo $$test; (echoing $test will give you ‘a’ as output)

When printing (echoing) a Boolean variable, if the Boolean value is true,


then the output will display 1 and if the value is false, it will display an
empty string (nothing). Null type is also converted to an empty string
when printed

Data types in PHP:


 String
 Integer
 Float
 Boolean (true or false (no capital T and F unlike python)
 Null
 Array
 Object
 Resource

Use echo gettype(variable) to print the data type of the variable


Use settype(variable,’data_type’) to change the data type

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()

to check if a variable contains data, use isset(variable) (without echo)


(returns true or false)

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

We can use the shorthand assignment ($a+=$b)

Increment operator: $a++ and ++$a


Decrement operator: $a-- and --$a

To check if something is numeric or not, use is_numeric() (returns true or


false) if a string containing only numbers is passed to this method, it will
return true

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”);

ex: $number = 123456789.12345;


echo number_format($number, 2, “.”, “,”)
output: 123,456,789.12

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.

Single quotes: echo ‘hello, I am ‘.$name.’<br>’; (here name is stored in


single quotes)
Double quotes: echo “hello, I am $name”.”<br>”; (here name is stored in
double quotes)

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()

lets say there a string:


$string = “Hello,
My name is Bhavya”;
To print it the way it is stored in the variable, use echo nl1br($string)
Just using echo to print the variable, it will just display the entire string in
a single line

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

To print html tags, use echo htmlentities($string);

html_entity_decode(“”) gives the HTML output of the source code.

Arrays:
$fruits=[“Banana”,”Apple”,”Orange”];
$fruits=new array(“Banana”,”Apple”,”Orange”);
Arrays can contain elements of multiple data types

Index starts from 0

Access individual elements: $fruits[0];


Changing values: $fruits[0]=”Peach”;

Check if array has element at a particular index:


isset($fruits[2]) //returns true (Orange)

append at the end:


$fruits[]=”banana”;
Count of array:
Count($fruits);

Add element:
array_push($fruits, element);

remove last element:


array_pop($fruits);

add element at the beginning:


array_unshift($fruit,”guava”);
remove element at the beginning:
array_shift($fruit);

split string into array:


explode(“,”, $string) //the first parameter tells us by what character do we
split the string

combine array elements into string:


implode(“&”, $fruits); //adds & after every element

check if element exists in array:


in_array(“Apple”,$fruits); //returns true or false

search for element in array:


array_search(“Apple”,$fruits); //returns the index of the element
searched. If element is not present, it will return false
merge two arrays:
array_merge($fruits, $vegetables);
$new_array = […$fruits, …$vegetables];

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”;
];

Get element by key:


$person[“name”];

Setting a new key-value pair:


$person[“channel”]=”non-existant”;

If a particular key-value pair doesn’t exist, use this,


If(! Isset($person[“address”])){
$person[“address”]=”unknown”;}

Shorthand:
$person[“address”] = $person[“address”] ?? ”unknown”;

Print keys of array:


array_keys($person);

print values of array:


array_values($person);

sort by keys or values:


ksort($person); //sorts by keys
assort($person); //sorts by values

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”;

null coalescing operator:


$name = isset($name)? $name:”Unknown”;

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++)
{
}

Advanced for loop, used with arrays:


foreach($fruits as $fruit) //$fruits is the array and $fruit is a random
variable

to get the index of the array elements, use foreach($fruits as $i=>$fruit){}


here, $i will contain the index

for associative arrays:


foreach($person as $key=>$value){}
this will give a problem in case the value is an array. To solve this, use
an if statement to check if it an array,
if(is_array($value)){
implode(“,”,$value);
}

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);)

Working with file system:


Magic constants:
 echo _ _ DIR _ _ will print the path of the current directory
(directory in which that file is stored)
 echo _ _ FILE _ _ will print the path of the file
 echo _ _ LINE _ _ will print the line number at which this statement
is written

creating a directory: mkdir(‘name’);


renaming a directory: rename(‘old_name’, ‘new_name’);
deleting directory: rmdir(‘name’);

get file content:


get_file_contents(‘file_name’);
put file content:
file_put_content(‘name’,’content’);
$file = file_get_content(‘URL’);

To check if file exists:


file_exists(‘name’); //returns true or false
OOP in PHP:

Classes and instances:


class Person{
public $name;
public $surname;
private $age;
}
$p = new Person(); //creating like an object of the class (similar to
python)
How to access those instance variables using the object:
$p->name = “Brad”;
$p->surname = “Traversy”;

(like in java we have the ‘.’ Operator (object.variable), in PHP that is


equivalent to the ‘->’ operator)

Constructor:
class Person{
public $name;
public $surname;
private $age;

public function _ _construct($name, $surname){


$this->name = name;
$this->surname = surname
}
}

Setters and getters:


class Person{
public $name;
public $surname;
private $age;

public function _ _construct($name, $surname){


$this->name = name;
$this->surname = surname
}
public function setAge($age){
$this->age = age;
}
public function getAge(){
return $this->age;
}
}

The static keyword:


public static $counter = 0;
to use the static keyword, we use the self keyword.

class Person{
public $name;
public $surname;
private $age;
public static $counter = 0;

public function _ _construct($name, $surname){


$this->name = name;
$this->surname = surname
self::$counter++; //increase counter every time a new
instance is created
}
public function setAge($age){
$this->age = age;
}
public function getAge(){
return $this->age;
}
public static function getCounter(){
return self::$counter;
}
}
echo Person::$counter
echo Person::
//to access static variables and methods outside the class, we just
mention the class name followed by ::, we don’t have to create an object.

In a class, we can also give variables a data type


Ex, public string $name;
public static int $counter = 0;
now, if we try to store values with any other data type, it will throw an
error.
If we want to also store null values along with the specific data types, we
have to write a ‘?’ symbol before the data type. Ex, public ?int $age; (this
will now store integer values and null values)

Inheritance is done using the keyword ‘entends’, just like Java.


Inside the child class, we can create the constructor and call the parent
constructor,
class Student extends Person{
public string studentId;
public function _ _construct($name, $surname, $studentId){
$this->studentId = $studentId;
parent::_ _ construct($name, $surname);
}
}

You might also like