02 PHP Basics
02 PHP Basics
02 PHP Basics
Sachin Ponde
Escaping Special Characters
If you enclose one set of quotation marks within
another, PHP will get confused about which quotation
marks are to be printed literally, and which ones are
simply used to enclose the string value.
PHP allows you to escape certain characters by
preceding them with a backslash (\).
There so-called escape sequences include:
Sequence What it represents
\n A line feed character
\t A tab
\r A carriage return
\” A double quotation mark
\’ A single quotation mark
<?php
echo “You said \”Hello\””; output: You said “Hello”
?>
<?php Escape sequences such as
echo “Welcome\nto\nPHP”;
those for line feeds (\n),
?>
Output:
carriage returns (\r) and
Welcome double quotation marks
to (\”) can only be
PHP understood by PHP parser
when they are themselves
<?php enclosed in double quotes.
echo ‘Welcome\nto\nPHP’;
?> If these escape sequences
Output: are enclosed in single
Welcome\nto\nPHP quotes, they will be printed
“as it is”.
<?php <?php
echo “Welcome\nto\nPHP”; echo ‘Welcome\nto\nPHP’;
?> ?>
Output: Output:
Welcome Welcome\nto\nPHP
to
PHP
Variable name itself to be variable
<?php
$attribute=‘price’;
${$attribute}=678;
echo $price;
?>
Output:
678
Destroying Variables
<?php
$car=‘Porshe’;
echo “Before unset(), my car is a $car”;
unset($car);
echo “After unset(), my car is a $car”;
?>
Output:
Before unset(), may car is a Porshe
After unset(), my car is a
(will generate ‘undefined variable’ error)
Inspecting Variable Contents
<?php print_r() function
$name=“Sanjay”; performs the same
$age=28; function as var_dump(),
var_dump($name); although it returns less
information.
var_dump($age);
print_r($name);
print_r($age);
?>
Output;
string 'Sanjay' (length=6)
int 28
Sanjay28
Understanding Data Types
<?php
//Boolean
$validUser=true;
//Integer
$size=15;
//Floating point
$temp=98.6;
//String
$cat=“Siamese”;
//Null
$here=null;
?>
Setting & Checking Variable Data
Types
<?php
PHP automatically
$whoami=‘Sachin’;
determines a variable’s
echo gettype($whoami); data type from the content
$whoami=99.8; it holds.
echo gettype($whoami); And if the variable’s
unset($whoami); content changes over the
echo gettype($whoami); duration of a script, the
?> language will automatically
Output: set the variable to the
string appropriate new data type.
(Type Juggling)
double
NULL (Error for undefined
variable)
PHP functions to test variable data
types
Function Purpose
is_bool() Tests if a variable holds a boolean value
is_numeric() Tests if a variable holds a numeric value
is_int() Tests if a variable holds a integer value
is_float() Tests if a variable holds a floating-point
value
is_string() Tests if a variable holds a string value
is_null() Tests if a variable holds a NULL value
is_array() Tests if a variable holds an array
Using Constatnts
<?php
define (‘PROGRAM’, ‘The Matrix’);
define(‘VERSION’ 11.7);
echo ‘Welcome to ‘.PROGRAM.’ (version’.VERSION.’)’;
?>
Output:
Welcome to The Matrix (version 11.7)
Using String Functions
Function What it does
empty() Tests if a string is empty
strlen() Calculates the number of characters in a string
strrev() Reverses a string
str_repeat() Repeats a string
substr() Retrieves a section of a string
strcmp() Compares two strings
str_word_count() Calculates the number of words in a string
str_replace() Replaces parts of a string
trim() Removes leading and trailing whitespace from a string
strtolower() Lowercases a string
strtoupper() Uppercases a string
ucfirst() Uppercases the first character of a string
ucwords() Uppercases the first character of every word of a
string
Function What it does
addslashes() Escapes special characters in a string with backslashes
stripslashes() Removes backslashes from a string
htmlspecialchars() Encodes special HTML characters within a string
strip_tags() Removes PHP and HTML code from a string
Checking for Empty string
<?php
$str=‘’;
echo (boolean)empty($str); //true
$str=null;
echo (boolean)empty($str); //true
$str=‘0’;
echo (boolean)empty($str); //true
unset($str);
echo (boolean)empty($str); //true
?>
Reversing and Repeating strings
<?php <?php
$str=‘Welcome to PHP’; $str=“One Small Step”;
echo strlen($str); echo strrev($str);
?> ?>
Output: Output:
14 petS llamS enO
<?php
$str=‘yo’;
echo str_repeat($str, 3);
?>
Output:
yoyoyo
Working with Substrings
<?php <?php
$str=‘Welcome to PHP’; $str=‘Welcome to PHP’;
echo substr($str,3,4); echo
substr($str,3,5).substr
?>
($str,-3,3);
?>
Output:
Output:
come PHP
come
Comparing, Counting and
Replacing Strings
<?php Strcmp() function performs a
$a=“hello”; case-sensitive comparison of
$b=“hello”; two strings, returning a
$c=“hEllo”; negative value if the first is
echo strcmp($a,$b); less than the second, a
echo strcmp($a,$c); positive value if it is the other
?> way around and zero if both
strings are equal.
Output: It calculates ASCII value of
0 the string and then compares
1 both strings to check that
they are equal, greater or less
from each other.
<?php <?php
$str=“The name’s bond, $str=‘john@domain.net’;
James Bond”; echo str_replace(‘@’,’
echo at ’,$str);
str_word_count($str); ?>
?>
Output: Output:
5 john at domain.net
Formatting Strings
<?php
//removing leading and trailing whitespaces
$str=‘ a b c ‘;
echo trim($str);
?>
Output:
a b c
<?php
//change string case
$str=‘Yabba Dabba Doo’;
echo strtolower($str);
echo strtoupper($str);
?>
Output:
yabba dabba doo
YABBA DABBA DOO
<?php
//change string case
$str=‘the yellow brigands’;
echo ucwords($str);
echo ucfirst($str);
?>
Output:
The Yellow Brigands
The yellow brigands
Working with HTML Strings
<?php
$str=“You’re awake, aren’t you?”;
echo addslashes($str);
?>
Output:
You\’re awake, aren\’t you?
<?php
//Remove slashes
$str=“John D’Souza says \”Catch you later\”.”;
echo stripslashes($str);
?>
Output:
John D’Souza says ”Catch you later”.
Using Numeric Functions
Function What it does
ceil() Rounds a number up
floor() Rounds a number down
abs() Finds the absolute value of a number
pow() Raises one number to the power of another
log() Finds the logarithm of a number
exp() Finds the exponent of a number
rand() Generates a random number
bindec() Converts a number from binary to decimal
decbin() Converts a number from decimal to binary
decoct() Converts a number from decimal to octal
hexdec() Converts a number from hexadecimal to decimal
number_format() Formats a number with grouped thousands and
decimals
printf() Formats a number using a custom specification
<?php <?php
$num=19.7; //return absolute value of no
//round number up $num= -19.7;
echo floor($num); echo abs($num);
?>
//round number down
Echo ceil($num); Output:
?> 19.7
Output: <?php
19 //calculate 4^3
20 echo pow(4,3);
?>
Output:
64
<?php
//generates random number
echo rand();
Output:
1,106,483
1?106?482*584
<?php
//Format as decimal number
printf(“%05d”,65);
Output:
00065
00239.000
I see 8 apples and 26.00 oranges
Working with Array Functions
Function What it Does
explode() Splits a string into array elements
implode() Joins array elements into a string
range() Generates a number range as an array
min() Finds smallest value in an array
max() Finds the largest value in an array
shuffle() Randomly rearranges the sequence of elements in an
array
array_slice() Extracts a segment of an array
array_shift() Removes an element from the beginning of an array
array_unshift() Adds an element to the beginning of an array
array_pop() Removes an element from the end of an array
array_push() Adds an element to the end of an array
array_unique() Removes duplicate elements from an array
Function What it Does
array_reverse() Reverses the sequence of elements in an array
array_merge() Combines two or more arrays
array_intersect() Calculates the common elements between two or more
arrays
array_diff() Calculates the difference between two arrays
in_array() Checks if a particular value exists in an array
array_key_exists() Checks if a particular key exists in an array
sort() Sorts an array
asort() Sorts an associative array by value
ksort() Sorts an associative array by keys
rsort() Reverse sorts an array
krsort() Reverse sorts an associative array by value
arsort() Reverse sorts an associative array by key
pos() This function returns the value of the current element in
an array.
Function What it Does
next() Moves internal pointer to the next element of array
count() Return the number of elements in an array
array_search() The array_search() function search an array for a
value and returns the key.
array_combine() creates an array by using the elements from one
"keys" array and one "values" array.
array_count_values() This function counts all the values of an array.
array_fill() This function fills an array with values.
array_change_key_case() This function changes all keys in an array to
lowercase or uppercase.
array_flip() This function flips/exchanges all keys with their
associated values in an array.
array_product() This function calculates and returns the product of
an array.
array_sum() This function returns the sum of all the values in
the array.
array_replace() This function replaces the values of the first array
with the values from following arrays.
<?php
//define string
$str=‘tinker,tailor,soldier,spy’;
?>
Output:
(‘tinker’, ‘tailor’, ‘soldier’, ‘spy’)
<?php
//define string
$arr=array(‘one’, ‘two’, ‘three’, ‘four’);
?>
Output:
One and two and three and four
<?php
//define array
$arr=range(1,1000);
print_r($arr);
?>
Output:
Generates an array containing all the values
between 1 and 1000
<?php
//define string
$data=array(‘Monday’, ‘Tuesday’, ‘Wednesday’);
?>
Output:
The array has 3 elements
<?php
//define array
$arr=array(7, 36, 5, 48, 28, 90, 91, 3, 67, 42);
Output:
Minimum is 3 and maximum is 91
Extracting Array Segment
<?php
//define array
$rainbow=array(‘violet’,’indigo’,‘blue’,’green’,
’yellow’,’orange’, ‘red’);
?>
Output:
(‘blue’, ‘green’, ‘yellow’)
(‘blue’, ‘green’, ‘yellow’)
Adding and Removing Array Elements
<?php
//define array
$movies=array(‘The Lion King’,’Super 30’,‘Mission Mangal’);
//remove the element from the beginning of array
array_shift($movies);
print_r($movies);
//remove the element from the end of array
array_pop($movies);
print_r($movies);
//add element to the end of array
array_push($movies, ‘Batla House’);
print_r($movies);
//add element to the beginning of array
array_unshift($movies, ‘Uri’);
print_r($movies);
?>
Output:
(‘Super 30’, ‘Mission Mangal’)
(‘Super 30’)
(‘Super 30’, ‘Batla House’)
(‘Uri’, ‘Super 30’, ‘Batla House’)
Removing Duplicate Array
<?php
//define array
$duplicates=array(‘a’,’b’,‘a’,’c’, ’e’,’d’,‘e’);
//remove duplicates
$uniques=array_unique($duplicates);
print_r($uniques);
?>
Output:
(‘a’, ‘b’, ‘c’ ‘e’, ‘d’)
Randomizing and Reversing Array
<?php
//define array
$rainbow=array(‘violet’,’indigo’,‘blue’,’green’,
’yellow’,’orange’, ‘red’);
//randomize array
shuffle($rainbow);
print_r($rainbow);
//reverse array
$arr=array_reverse($rainbow);
print_r($arr);
?>
Output:
(‘red’, ‘orange’, ‘yellow’, ‘green’, ‘blue’, ‘indigo’,
‘violet’)
Searching Array
<?php
//define array
$cities=array(‘London’,’Paris’,‘Barcelona’,’Lisbon’,
’Zurich’);
Output:
1 (true)
<?php
//define array
$cities=array(“United Kingdom”=>”London”,”United
States”=>“Washington”, “France”=>”Paris”,”India”
=>”Delhi”);
Output:
1 (true)
Sorting Array
<?php
//define array
$data=array(15, 81, 14, 74, 2);
Output:
(2, 14, 15, 74, 81)
<?php
//define array
$profile=array(“fname”=>”Virat”,
“lname”=>”Kohli”
“sex”=>”male”
“sector”=>”Criketer”);
//sort by value
asort($profile);
print_r($profile);
ksort($profile);
print_r($profile);
?>
Output:
(“sector”=>”Cricketer”,
“lname”=>”Kohli”,
“fname”=>”Virat”,
“sex”=>”male”)
(“fname”=>”Virat”,
“lname”=>”Kohli”,
“sector”=>”Cricketer”,
“sex”=>”male”)
Merging Array
<?php
//define array
$dark=array(‘black’, ‘brown’, ‘blue’);
$light=array(‘white’, ‘silver’, ‘yellow’);
//merge arrays
$colors=array_merge($dark, $light);
print_r($colors);
?>
Output:
(‘black’, ‘brown’, ‘blue’, ‘white’, ‘silver’, ‘yellow’)
Comparing Arrays
<?php
//define array
$orange=array(‘red’, ‘yellow’);
$green=array(‘yellow’, ‘blue’);
Output:
(‘yellow’)
(‘red’)
<html>
<body>
<?php
$fname=array(“Rohit",“Virat",”Ma
hendra");
$age=array(“33",“35","43");
$c=array_combine($fname,$age);
print_r($c);
?>
</body>
</html>
Output:
Array ( [Rohitr] => 33 [Virat] => 35 [Mahendra] => 43 )
<html>
<body>
<?php
$a=array("A","Cat","Dog","A","Dog“, “A”);
print_r(array_count_values($a));
?>
</body>
</html>
Output:
Array ( [A] => 3 [Cat] => 1 [Dog] => 2 )
array_fill(index, number, value)
<html>
<body>
<?php
$a1=array_fill(3,4,"blue");
$b1=array_fill(0,1,"red");
print_r($a1);
echo "<br>";
print_r($b1);
?>
</body>
</html>
Output:
Array ( [3] => blue [4] => blue [5] => blue [6] => blue )
Array ( [0] => red )
<html>
<body>
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$result=array_flip($a1);
print_r($result);
?>
</body>
</html>
Output:
Array ( [red] => a [green] => b [blue] => c [yellow] => d )
<html>
<body>
<?php
$a=array(5,5);
echo(array_product($a));
?>
</body>
</html>
Output:
25
<html>
<body>
<?php
$a=array(5,15,25);
echo array_sum($a);
?>
</body>
</html>
Output:
45
array_replace(array1, array2, array3, ...)
<html>
<body>
<html>
<body>
<?php
$a1=array("red","green");
<?php
$a2=array("blue","yellow");
$a1=array("red","green");
$a3=array("orange","burgundy");
$a2=array("blue","yellow");
print_r(array_replace($a1,$a2,$a3));
print_r(array_replace($a1,$a2));
?>
?>
</body>
</body>
</html>
</html>
Output:
Output:
Array ( [0] => blue [1] => yellow )
Array ( [0] => orange [1] => burgundy )
<html>
<body>
<?php
$age=array(“Rohit"=>"33",“Virat"=>“35",“Mahendra"=>"43");
print_r(array_change_key_case($age,CASE_UPPER));
?>
</body>
</html>
Output:
Array ( [ROHIT] => 33 [VIRAT] => 35 [MAHENDRA] => 43 )
<html>
<body>
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
</body>
</html>
Output:
Peter
$now=time();
echo "<br>".$now;
echo "<br>Today's date is ".date("d M Y h:m a", $now);
$str="Aug 22 2019";
echo "<br>".date("d M Y",strtotime($str));
?>
Output:
Array ( [seconds] => 15 [minutes] => 37 [hours] => 6 [mday] => 22 [wday] => 4
[mon] => 8 [year] => 2019 [yday] => 233 [weekday] => Thursday [month] =>
August [0] => 1566455835 )
Today's date is 22 8 2019 and Time is 6:37:15
1566455835
Today's date is 22 Aug 2019 06:08 am
22 Aug 2019
22 Aug 2019
Characters used in Date()
Character What it Means
d Day of the month (numeric)
D Day of the week (string)
l Day of week (string)
F Month (string)
M Month (string)
m Month (numeric)
Y Year
h Hour (in 12-hour format)
H Hour (in 24-hour format)
a AM or PM
i Minute
s Second
<?php
If(checkdate(2,30,2008))
{
echo ‘Date is Valid’;
}
else
{
echo ‘Date is invalid’;
}
?>
Output:
Date is invalid
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: