Applications Development and Emerging Technologies Reviewer
Applications Development and Emerging Technologies Reviewer
Applications Development and Emerging Technologies Reviewer
TECHNOLOGIES REVIEWER
MODULE 3
PHP Arrays and User Defined
Functions
PHP Arrays
Array
ARRAY
Output:
$fruit = array("orange",
"apple",
Functions for visualizing arrays "grapes",
"banana");
print_r() function - short for print echo "<pre>";
recursive. This takes an argument of any var_dump($fruit);
type and prints it out, which includes echo "</pre>";
printing all its parts recursively.
<?php
$fruit = array("orange",
"apple",
"grapes",
"banana"); Looping through array elements
echo "<pre>";
print_r($fruit); foreach() function - is a statement used
echo "</pre>"; to iterate or loop through the element in an
?> array. With each loop, a foreach
statement moves to the next element in an
array.
Multidimensional arrays
Example:
<?php
$person = array(
'Leader' => array(
'First Name' => 'Juan',
'Last Name' => 'Dela
Cruz', Output:
'Date of Birth' =>
'April 3, 1986',
'Gender' => 'Male'),
'Assistant' => array(
'First Name' => 'Rica',
'Last Name' => 'San
Pedro',
'Date of Birth' =>
'January 8, 1980',
'Gender' => 'Female'),
'Member' => array(
'First Name' => 'Jose',
'Last Name' => 'Dela
Paz',
'Date of Birth' =>
'March 2, 1985',
'Gender' => 'Male') Sorting
);
Function Description
foreach($person as $pkey => sort($array) Sort by value;
$parr){
assign new
numbers as the
echo "<h2>$pkey</h2>";
keys
foreach($parr as $key => rsort($array) Sorts by value in
$value){ reverse order;
echo "$key: assign new
$value<br/>";
number as the Output:
keys
asort($array) Sorts by value;
keeps the same
key
arsort($array) Sorts by value in
reverse order;
keeps the same
key
ksort($array) Sorts by key
krsort($array) Sorts by key in
reverse order
usort($array, Sorts by a function
functionname)
Example:
<?php Example:
$fruit = array(
"orange", "apple", <?php
"grapes", "banana", $fruit = array(
"guava", "blue berry"); "orange", "apple",
"grapes", "banana",
sort($fruit); //sort array in "guava", "blue berry");
ascending
echo "<pre>"; asort($fruit);
print_r($fruit); echo "<pre>";
echo "</pre>"; print_r($fruit);
echo "</pre>";
rsort($fruit); //sort array in
descending arsort($fruit);
echo "<pre>"; echo "<pre>";
print_r($fruit); print_r($fruit);
echo "</pre>"; echo "</pre>";
?> ?>
Output:
Output:
Example:
<?php
$fruit = array(
'1010' => "orange",
'1002' => "apple",
'1023' => "grapes",
'1006' => "banana",
'1015' => "guava",
'1009' => "blue berry");
ksort($fruit);
echo "<pre>";
print_r($fruit);
echo "</pre>"; PHP USER DEFINED FUNCTIONS
krsort($fruit); Functions
echo "<pre>";
print_r($fruit); - is a group of PHP statements that
echo "</pre>"; performs a specific task. Functions are
?> designed to allow you to reuse the same
code in different locations.
Predefined functions
function name(param){
//code to be executed by the
function
}
Where
function
- is the keyword used to declare a function
name
- is the name of the function or function Output:
identifier
param
- is the formal parameters of the function.
Parameter must follow the rule of naming
identifier.
Output:
Output:
Nested function
Example:
Example: <?php
function displayPerson(){
function qoutient($x, $y){ function name(){
return $x/$y; echo "Juan Dela Cruz";
} }
}
function remark($grade){
if($grade >= 75){ name();
return true; ?>
} else{
return false;
}
}
printf("The qoutient is
%.2f<br/>", qoutient(7,3));
if(remark(80)){
echo "passed";
} else { Output:
echo "failed";
}
Example:
<?php
function displayPerson(){
function name(){
echo "Juan Dela Cruz";
}
}
displayPerson();
name();
?>
Output:
Example:
<?php
Output: $str = "This is global
variable";
function f(){
global $str;
Variable scope echo "function f () was
called<br>";
Global Variables - is one that declared echo "$str<br>";
outside a function and is available to all }
parts of the program. f();
?>
Local Variables - is declared inside a
function and is only available within the
function in which it is declared.
using variables
Example:
Output:
<?php
$str = "This is global
variable";
function f(){ Example:
echo "function f () was
called<br>"; <?php
echo "$str<br>"; function f(){
} $str = "This is local
f(); variable";
?> }
f();
echo "Displaying local variable:
" ;
echo $str;
?>
counter(4);
counter(3);
counter(8);
counter(6);
?>
Output:
Example:
<?php
function f(){ Output:
global $str;
$str = "This is local
variable";
}
f();
echo "Displaying local variable:
" ; Summary
echo $str; • Array is used to aggregate a series of
?> similar items together.
• Array index references a corresponding
value.
• Array index can be simple numerical or
have some direct correlation to the value.
• Array index is also known as Array Keys.
• print_r function is used to print the array
structure.
• var_dump function is same as print_r
function except it adds additional
Output: information about the data of each
element.
• The foreach statement is use to iterate
through the element in an array.
• Using foreach statement you can display
Example: both the keys and value of each element
in the array.
<?php • PHP provides functions for array
function counter($value){ manipulation such as sort (), rsort(),
static $count = 0; asort(), arsort(), ksort(), krsort(), and
$count += $value; usort() functions.
echo "The value of the • sort(), asort(), and ksort() functions
counter is $count<br>"; are used to sort elements in the array in
} ascending order.
• rsort(), arsort(), and krsort() functions Numeric array
are used to sort elements in the array in
descending order. - An array with a numeric index. Values
• sort() and rsort() does not maintain its are stored and accessed in linear fashion.
index reference for each values.
• asort(), ksort(), arsort(), and krsort() Associative array
maintains its reference for each values.
• asort() and arsort() used to sort - An array with strings as index. This store
elements by values. element values in association with key
• ksort() and krsort() used to sort values rather than in a strict linear index
elements by keys. order.
• Functions is a group of PHP statements
that performs a specific task. Multidimensional array
• Functions can be user defined generally
defined by the user of the program and - An array containing one or more arrays
predefined that are build in using libraries. and values are accessed using multiple
• You use functions in different ways. indices
Function can only do something without
passing values. You can pass values to a NOTE - Built-in array functions is given in
function, and you can ask functions to function reference PHP Array Functions
return a value.
• function keyword is used in PHP to Numeric Array
declare a function. Following is the example showing how to
• A function that is declared inside a create and access numeric arrays.
function is said to be hidden. Here we have used array() function to
• To gain access to a variable that is create array. This function is explained in
outside from the function we use the function reference.
global keyword.
• We use static keyword to declare a <html>
variable inside a function that will act as <body>
accumulator variable this will let the
program remember the last value of the <?php
variable that was used. /* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
SUPPLEMENTARY
foreach( $numbers as $value ) {
ARRAY echo "Value is $value <br />";
}
An array is a data structure that stores one
or more similar type of values in a single /* Second method to create array. */
value. For example, if you want to store $numbers[0] = "one";
100 numbers then instead of defining 100 $numbers[1] = "two";
variables its easy to define an array of $numbers[2] = "three";
100 length. $numbers[3] = "four";
$numbers[4] = "five";
There are three different kinds of arrays,
and each array value is accessed using an foreach( $numbers as $value ) {
ID c which is called array index. echo "Value is $value <br />";
}
?>
echo "Salary of mohammad is ".
</body> $salaries['mohammad'] .
</html> "<br />";
echo "Salary of qadir is ".
This will produce the following result – $salaries['qadir']. "<br />";
echo "Salary of zara is ".
Output: $salaries['zara']. "<br />";
</body>
</html>
Output: <?php
$vec_1 =
Marks for mohammad in physics : 35 array("moshe","david","john");
echo "simple array of strings"; Output:
for($i=0; $i<3; $i++)
{
echo "<BR>".$vec_1[$i];
}
?>
Output:
<?php
<?php $vec = array(2,4,5,123,2221,”sda”);
$vec_1 = var_dump($vec);
array(100=>"moshe",101=>"david",102 ?>
=>"john");
echo "simple array of strings and their Output:
keys";
echo "<BR>".$vec_1[100];
echo "<BR>".$vec_1[101];
echo "<BR>".$vec_1[102]; • Using var_dump() function we can print
?> out more than one array.
Output: <?php
$vec_1 = array(2,4,5,123,2221);
$vec_2 = array(24,442,32,84,110);
$vec_3 = array(10,20,30,40,50);
var_dump($vec_1,$vec_2,$vec_3);
?>
Output:
<?php
$vec_1 =
array("m"=>"moshe","d"=>"david","j"=
>"john");
echo "simple array of strings and their
keys";
echo "<BR>".$vec_1["m"];
echo "<BR>".$vec_1["d"];
echo "<BR>".$vec_1["j"];
?>
<?php
$matrix = array();
$matrix[0] = array("a","b");
$matrix[1] = array("c","d");
echo $matrix[0][0];
echo $matrix[0][1];
echo $matrix[1][0];
echo $matrix[1][1];
?>
Output:
Output:
Array Inner Structure
• PHP arrays behave like ordered map.
As such, they allow various
possibilities:
PHP arrays can be used to simulate
different types of structures (e.g., map, <?php
queue, stack etc...). $vec =
PHP arrays can have unique keys, both [2=>"dave",1=>"ron",0=>"chen",3=>"ra
numeric and textual. When using numeric n"];
ones, they don't need to be sequential. list($a,$b,$c) = $vec;
echo "<br>a=$a";
Multi Dimensional Arrays echo "<br>b=$b";
• A multidimensional array is an array that echo "<br>c=$c";
each one of its elements is another array. ?>
<?php
Output: $vec_1 = array(1,2,3);
$vec_2 = array(3,4,5,6);
$vec_3 = $vec_1 + $vec_2;
var_dump($vec_3);
?>
<?php
$matrix = [
["haim", "michael", 344537565],
["mosh", "solomon", 452234343],
The ‘==’ and ‘===’ Operators
["ron","kalmon",453234234]
The '==' operator (equality) returns true
];
if the following condition fulfills:
foreach ($matrix as list($fname,
1. The two arrays contain the same
$lname,$id))
elements.
{
The '===' operator (non identity)
echo "fname:$fname lname:$lname
returns true if each one of the following
id:$id ";
two conditions fulfills:
}
1. The two arrays contain the same
?>
elements.
2. The two arrays have their identical
Output:
elements in the same position.
<?php
//$a =
['a'=>'avodado','b'=>'bamba','c'=>'calco'
];
//$b =
['b'=>'bamba','a'=>'avodado','c'=>'calco'
];
$a = [123,455,323];
$b = [323,123,455];
if($a==$b)
{
echo "a and b equal";
}
else
{
echo "a and b not equal";
}
The ‘+’ Operator ?>
• Using the + operator on two arrays we
will get a union of the two arrays. Result: a and b not equal
• Union of two arrays will include a union
of the keys each one of the two arrays
have and the values assigned with each
one of them.
The ‘!=’ and ‘!==’ Operators var_dump($vec_2!=$vec_5); //false
The '!=' operator (inequality) returns var_dump($vec_2!==$vec_5); //true
true if the following condition doesn't ?>
fulfill:
1. The two arrays contain the same Output:
elements.
The '!==' operator (non identity) returns
true if at least one of the following two
conditions doesn't fulfill:
Example <?php
$vec = array(1,2,3,4,5,6,7,8);
<?php echo count($vec);
$vec_1 = array(1,2,3); ?>
$vec_2 = array(1,2,3);
$vec_3 = array(0=>1, 1=>2, 2=>3); Output:
$vec_4 = array(12=>1, 3=>2, 4=>3);
$vec_5 = array(1=>2, 0=>1, 2=>3);
var_dump($vec_1==$vec_2); //true
var_dump($vec_1===$vec_2); //true
var_dump($vec_1!=$vec_2); //false
The is_array () Function.
var_dump($vec_1!==$vec_2); //false
Calling the is_array () function on a
echo "<BR>";
variable returns true if that variable holds
var_dump($vec_2==$vec_3); //true
an array, and false if isn't.
var_dump($vec_2===$vec_3); //true
var_dump($vec_2!=$vec_3); //false
<?php
var_dump($vec_2!==$vec_3); //false
$vec_1 = array(1,2,3,4,5,6,7,8);
?>
$vec_2 = 123;
if(is_array($vec_1))
Output:
echo "<BR>vec_1 is an array";
else
echo "<BR>vec_1 is not an array";
if(is_array($vec_2))
echo "<BR>vec_2 is an array";
Example else
echo "<BR>vec_2 is not an array";
<?php ?>
echo "<BR>";
var_dump($vec_2==$vec_4); //false Output:
var_dump($vec_2===$vec_4); //false
var_dump($vec_2!=$vec_4); //true
var_dump($vec_2!==$vec_4); //true
echo "<BR>";
var_dump($vec_2==$vec_5); //true
var_dump($vec_2===$vec_5); //false
The isset () Function
Calling the isset () function can tell us if a The isset () function doesn't return true
specific key already exists in our array... or for array keys that were set together with
not. null as its value.
Output:
<?php
$vec = array('a'=>1,'b'=>2,'c'=>3);
if(array_key_exists('a',$vec)) echo
"<BR>'a' key exists";
if(array_key_exists('b',$vec)) echo
"<BR>'b' key exists";
if(array_key_exists('c',$vec)) echo
"<BR>'c' key exists";
if(array_key_exists('d',$vec)) echo
"<BR>'d' key exists";
if(array_key_exists('e',$vec)) echo
"<BR>'e' key exists";
?>
Output:
The array_reverse () Function
This function returns a new array, which is
the result of reversing the order of a given
one.
<?php current ()
$vec_1 =
array("a","b","c","d","f","g","h"); - gets the current element's value.
echo "<BR>before...<BR>";
var_dump($vec_1); key ()
$vec_2 = array_reverse($vec_1);
echo "<BR>after...<BR>"; - gets the current element's key.
var_dump($vec_2);
?> <?php
$vec =
Output: array("a","b","c","d","f","g","h");
reset($vec);
while(key($vec)!==null)
{
echo key($vec)." is the key and
".current($vec)." is the value<BR>";
next($vec);
}
?>
Output:
reset () to finish.
- resets the pointer to the array initial foreach (___ as ___ => ___)
position. {
…
next () …
…
- moves the pointer to the next element. }
Output:
<?php
$vec =
array('moshe','david','michael','mike');
foreach($vec as $key_var =>
$value_var)
{ The array_combine () Function
echo "<BR>$key_var : $value_var"; The array_combine (array $keys, array
} $values) function receives two arrays
?> and creates a new array. The keys are the
values of the first array elements. The
Output: values are the values of the second array
elements.
<?php
$values_vec =
array('moshe','david','michael','mike');
$keys_vec =
The following is an alternative syntax for array('mosh','dav','mich','mik');
using the foreach. $vec =
array_combine($keys_vec,$values_vec
construct );
print_r($vec);
foreach (___ as ___) ?>
{
… Output:
…
…
}
Output:
<?php
$japan_cars =
array("T" => "Toyota", "M" => "Mazda",
"S" => "Suzuki", "Y" => "Yamaha");
$usa_cars =
array("C" => "Chevrolet", "P" =>
"Pontiac", "C" => "Cryzler");
echo "<P>before ...<BR>";
var_dump($japan_cars);
echo "<BR>";
var_dump($usa_cars);
sort($japan_cars);
asort($usa_cars);
echo "<P>after...<BR>";
var_dump($japan_cars);
echo "<BR>"; Both sort () and asort () allows passing a
var_dump($usa_cars); second optional parameter, that configures
?> the operation. This second optional
parameter can be one of the following
Output: possibilities:
SOFT_REGULAR
SORT_NUMERIC
SORT_STRING
rsort () function
Array Shuffle
Calling the shuffle () function will
scramble arrays' elements in a randomize
order.
Output:
Arrays as Stacks
The array_push () and array_pop ()
functions enable us to use an array as a
stack.
int array_push (array &$array, mixed
$var [, mixed $...])
This function pushes the passed values
onto the end of the array. The array's
length is increased by the number of the
passed variables. This function returns the
number of elements, the array has.
mixed array_pop (array &$array)
This function returns the last value of the
array and shorten its length by one.
Arrays as Sets
The array_intersect () function returns
an array containing all the values of
array1 that are present in all other arrays.
The keys are preserved.
<?php
define('IMAGE_TYPES', ['jpg', 'jpeg',
Array Dereferencing 'png', 'gif']);
foreach(IMAGE_TYPES as $v) {
- As of PHP 5.5 it is possible to echo "<h2>".$v."</h2>";
dereference the array directly. }
echo "<h1>".IMAGE_TYPES[0]."</h1>";
<?php ?>
echo ["david","anat","limor","ilana"][0];
?> Output:
Result: david
The ?? Operator
The ?? operator, that was introduced in
PHP 7, is also known as the isset ternary
operator, is a shorthand notation for
performing isset () checks in the ternary
operator.
Example
<?php
function writeMsg() {
echo "Hello world!";
} The following example has a function
writeMsg(); // call the function with two arguments ($fname and
?> $year):
Output: Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year
<br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978"); In the following example we try to send
familyName("Kai Jim", "1983"); both a number and a string to the function,
?> but here we have added the strict
declaration:
Output:
Example
Example
You can specify a different return type,
<?php declare(strict_types=1); // strict than the argument types, but make sure
requirement the return is the correct type:
function sum(int $x, int $y) {
$z = $x + $y; Example
return $z;
} <?php declare(strict_types=1); // strict
echo "5 + 10 = " . sum(5, 10) . "<br>"; requirement
echo "7 + 13 = " . sum(7, 13) . "<br>"; function addNumbers(float $a, float $b)
echo "2 + 4 = " . sum(2, 4); : int {
?> return (int)($a + $b);
}
Output: echo addNumbers(1.2, 5.2);
?>
Output:
<body> </body>
</html>
<?php
/* Defining a PHP Function */ This will display following result –
function writeMessage() {
echo "You are really a nice person, Output:
Have a nice time!";
} Sum of the two numbers is : 30
printMe("This is test");
- is used to aggregate a series of similar
printMe();
items together, arranging and
?>
dereferencing them in some specific way.
</body>
• Each member of the array index
</html>
references a corresponding value and can
be a simple numerical reference to the
This will produce following result –
value’s position in the series, or it could
have some direct correlation to the value.
Output:
• PHP array does not need to declare how
This is test
many elements that the array variable
have.
Dynamic Function Calls
It is possible to assign function names as • Array index in PHP can be also called as
strings to variables and then treat these array keys.
variables exactly as you would the
function name itself. Following example • Array can be used as ordinary array
depicts this behaviour. same as in C and C++ arrays.
Syntax
foreach($arr as $value){
//do something with $value
variable
}
foreach($arr as $key => $value){
//do something with $key
and/or $value variable
}
Output:
foreach($person as $value){
echo "$value <br/>"; keeps the same
} key
echo "<p/>"; ksort($array) Sorts by key
foreach($person as $key => krsort($array) Sorts by key in
reverse order
$value){
usort($array, Sorts by a function
echo "$key: $value <br/>"; functionname)
}
?>
PHP USER DEFINED FUNCTIONS
Functions
Predefined functions
Output:
- functions that are built-in into PHP to
perform some standard operations
Syntax
function name(param){
//code to be executed by the
function
}
Arrays: Sorting
Where
Function Description
sort($array) Sort by value;
function
assign new
numbers as the
keys - is the keyword used to declare a function
rsort($array) Sorts by value in
reverse order; name
assign new
number as the - is the name of the function or function
keys identifier
asort($array) Sorts by value;
keeps the same
key
arsort($array) Sorts by value in
reverse order;
param Output:
Output:
Local Variables
Example function that returns a value
- is declared inside a function and is only
function qoutient($x, $y){ available within the function in which it is
return $x/$y; declared.
}
Static Variables
function remark($grade){
if($grade >= 75){ - is used to retain the values calls to the
return true; same function.
} else{
Example:
return false;
}
<?php
}
$str = "This is global
variable";
printf("The qoutient is
function f(){
%.2f<br/>", qoutient(7,3));
echo "function f () was
if(remark(80)){
called<br>";
echo "passed";
echo "$str<br>";
} else {
}
echo "failed";
f();
}
?>
Output:
Example:
Output: <?php
$str = "This is global
variable";
function f(){
global $str;
Global Variables
echo "function f () was
called<br>";
- is one that declared outside a function
echo "$str<br>";
and is available to all parts of the program.
}
f();
?>
echo $str;
?>
Output:
Output:
Example:
<?php MODULE 4
function f(){
PHP Predefined Functions – Constants,
Files and Mathematical Functions
$str = "This is local
variable";
} PHP PREDEFINED FUNCTIONS
f();
echo "Displaying local variable: Using Constant
" ;
echo $str; define () functions.
?>
- used to declare constants. A constant
can only be assigned a scalar value, like a
string or a number. A constant’s value
cannot be changed.
Syntax:
define(‘NAME’,’value’);
Output:
Example:
<?php
define('MAX_VALUE', 10);
Example:
for($i=5; $i<MAX_VALUE;$i++){
echo $i." ";
<?php
}
function f(){
//MAX_VALUE = 20; is invalids
global $str;
?>
$str = "This is local
variable";
}
f();
echo "Displaying local variable:
" ;
redefinitions, variable reassignments, and
other possible problems.
Syntax:
include(“filename.inc”);
include_once(“filename.inc”);
Output: require(“filename.inc”);
require_once(“filename.inc”);
You may write the file with an extension require() function (file not found)
name of .inc rather than .php to serve as a
fragment of your program code. Example:
MATHEMATICAL FUNCTION:
rand () function
Output:
- used to generate random integers
- syntax
int rand(void)
int rand(int $min, int $max)
include() function(file exists)
ceil () function.
Example:
- returns the next highest integer by
rounding the value upwards
<html>
- syntax
<head>
float ceil(float $value)
<title></title>
<meta http-equiv="Content-
floor () function
Type" content="text/html; charset-
UTF-8"> - returns the next lowest integer by
</head> rounding the value downwards
<body> - syntax
<?php float floor(float $value)
include("header.inc")?>
<h4>Content</h4> min () function
The quick brown fox jumps
over the lazy dog near the bank of - Return the smallest value
the rivers - syntax
</body> mixed min(array $values) mixed
</html> min(mixed $values1, mixed
$values2[,mixed $...])
max () function
Example:
<?php
for($i=0;$i < 5; $i++){
$xgen[] = rand();
Output:
}
echo "x values: ";
foreach ($xgen as $num){
echo $num." ";
}
echo "<br/>";
echo "min: ".min($xgen)." max:
".max($xgen); MATHEMATICAL FUNCTION
echo "<br/>";
for($i=0; $i<5; $i++){
number_format () function
$ygen[] = rand(5,10);
}
- Format a number with grouped thousand
echo "y values: ";
- syntax
foreach($ygen as $num){
string number_format (
echo $num." "; float $number
} [, int $decimals = 0 ] )
echo "<br />";
echo "min: ".min($ygen)." max string number_format (
".max($ygen); float $number ,
echo "<br />"; int $decimals = 0 ,
echo "ceil(3.01): string $dec_point = '.' ,
".ceil(3.01)."<br/>"; string $thousands_sep = ',' )
echo "floor(3.91):
".floor(3.91)."<br/>"; Example:
?>
<?php
$price = 217795.75;
echo
number_format($price)."<br>";
echo number_format($price, 2,
'.', '')."<br>";
echo number_format($price, 2,
'.',',')."<br>";
?> foreach($fruitArr as $fruit)
echo $fruit." ";
$fruitStr = implode(",",
$fruitArr);
echo "<p/>Fruit string
(implode) : $fruitStr";
Output:
unset ($fruitArr);
echo "<p/> Fruit list
(unset) <pre>"; print_r($fruitArr);
echo "</pre>";
unset function
implode function.
FUNCTION FOR STRING
- join array elements to form a string MANIPULATION:
- syntax:
string implode ( string $glue ,
strlen function
array $pieces )
string implode ( array $pieces )
- return the value length of a string
- syntax:
unset(), explode(), implode()
int strlen (string $string)
Example:
strpos function
<?php
- find the position of the first occurrence of
$fruitArr = array('orange', a substring in a given string
'apple', 'grapes', 'mango',
'banana');
- syntax: printf("Sub String \"fox
int strpos ( string $haystack , jumps\": %s <br/>", substr($str, 16,
mixed $needle [, int $offset = 0 9));
]) ?>
strrev function
strtoupper function
strip_tags () function
<?php
$str = "the quick bron fox
jumps...";
echo ucfirst($str)."<br/>";
echo ucwords($str)."<br/>";
$str = " sample
string ";
echo "<pre>"; var_dump($str);
echo "</pre>";
$str = ltrim($str);
echo "<pre>"; var_dump($str); DATE MANIPULATION
echo "</pre>";
$str = rtrim($str); date () Function
echo "<pre>"; var_dump($str);
echo "</pre>"; - used to format a local time or date
$str = " sample - returns a string formatted according to
string "; the given format string.
echo "<pre>"; var_dump($str); - syntax:
echo "</pre>"; string date ( string $format [, int
$str = trim($str); $timestamp = time() ] )
echo "<pre>"; var_dump($str);
Format Description Example
echo "</pre>"; character returned
$str = "<p>paragraph</p><hr/><a values
href='#'>link</a>"; DAY
d Day of the month, 2 01 to 31
$strA = strip_tags($str); digits with leading zeros
echo "<pre>"; var_dump($strA); D A textual representation Mon
echo "</pre>"; of a day, three letters through
Sun
$strB = strip_tags($str, j Day of the month 1 to 31
'<a><p>'); without leading zeros
l A full textual Sunday Y A full numeric Examples:
representation of the through representation of a year, 1999 or
day of the week Saturday 4 digits 2003
N ISO-8601 numeric 1 (for y A two digit representation Examples:
representation of the Monday) of a year 99 or 03
day of the week (added through 7
in PHP 5.1.0) (for Format Description Example
Sunday) character returned
S English ordinal suffix for st, nd, rd values
the day of the month, 2 or th. TIME
characters Works
a Lowercase Ante am or pm
well with j
meridiem and Post
w Numeric representation 0 (for meridiem
of the day of the week Sunday)
A Uppercase Ante AM or PM
through 6
meridiem and Post
(for
meridiem
Saturday)
B Swatch Internet time 000 through
z The day of the year 0 through
999
(starting from 0) 365
g 12-hour format of an 1 through 12
W ISO-8601 week number Example:
hour without leading
of year, weeks starting 42 (the
zeros
on Monday 42nd week
G 24-hour format of an 0 through 23
in the
hour without leading
year)
zeros
h 12-hour format of an 01 through12
Format Description Example hour with leading
character returned zeros
values H 24-hour format of an 00 through 23
MONTH hour with leading
F A full textual January zeros
representation of a through i Minutes with leading 00 to 59
month, such as December zeros
January or March s Seconds, with leading 00 through 59
m Numeric 01 zeros
representation of a through u Microseconds Example:
month, with leading 12 654321
zeros
M A short textual Jan
Format Description Example
representation of a through
character returned
month, three letters Dec
values
n Numeric 1 through
TIMEZONE
representation of a 12
month, without leading e Timezone identifier Examples:
zeros UTC, GMT,
Atlantic/Azor
t Number of days in the 28
es
given month through
31 I Whether or not the 1 if Daylight
date is in daylight Saving Time,
saving time 0 otherwise.
Format Description Example O Difference to Example:
character returned Greenwich time +0200
values (GMT) in hours
YEAR P Difference to Example:
L Whether it’s a leap year 1 if it is a Greenwich time +02:00
leap year, (GMT) with colon
0 between hours and
otherwise. minutes
o ISO-8601 year number. Examples: T Timezone Example:
This has the same value 1999 or abbreviation EST, MDT…
as Y, except that if the 2003 z Timezone offset in -43200
ISO week number (W) seconds. The offset through
belongs to the previous for timezones west of 50400
or next year, that year is UTC is always
used instead. negative, and for
those east of UTC is
always positive.
[, int $second = date("s")
[, int $month = date("n")
Format Description Example [, int $day = date("j")
charact returned values
[, int $year = date("Y")
er
[, int $is_dst = -1 ]]]]]]] )
FULL DATE/TIME
c ISO 8601 2004-02-
date 12T15:19:21+00 strtotime () function
:00)
r >> RFC Example: Thu, - parse any English textual datetime
2822 21 Dec 2000 description into a Unix timestamp
formatted 16:01:07 + 0200 - syntax:
date int strtotime ( string $time
U Seconds See also time () [, int $now = time() ] )
since the
Unix Epoch SUPPLEMENTARY
(January 1,
1970,
00:00:00 Constant in PHP
GMT) 1. Constants are PHP container that
remain constant and never change
PHP: Documentation 2. Constants are used for data that is
unchanged at multiple places within our
Example: program.
3. Variables are temporary storage while
<?php Constants are permanent.
echo date("l"); 4. Use Constants for values that remain
echo "<br/>"; fixed and referenced multiple times.
echo date('l jS \of F Y h:i:s
A'); Rules for defining constant.
?> 1. Constants are defined using PHP's
define () function, which accepts two
arguments: The name of the constant, and
its value.
Syntax:
<?php
mktime () function
define('ConstName', 'value');
?>
- get the unix timestamp (January 1,
1970) for a given date. (With strict
notice) Valid and Invalid Constant declaration:
- same as time () function (without strict
notice) <?php
- syntax:
int mktime ([ int $hour = date("H") //valid constant names
[, int $minute = date("i") define('ONE', "first value");
define('TWO', "second value"); Subtraction of two numbers using
define('SUM 2',ONE+TWO); constant
<h2>USD/EUR Currency
Conversion</h2>
<?php
PHP Math Functions
//define exchange rate
//1.00 USD= 0.80 EUR Function Description
define('EXCHANGE_RATE',0.80); abs() Returns the absolute
(positive) value of a
//define number of dollars number
$dollars=150; acos() Returns the arc
cosine of a number
//perform conversion and print result acosh() Returns the inverse
$euros=$dollars*EXCHANGE_RATE; hyperbolic cosine of a
number
echo "$dollars USD is equivalent to asin() Returns the arc sine
:$euros EUR"; of a number
?> asinh() Returns the inverse
hyperbolic sine of a
number
Output
atan() Returns the arc
tangent of a number
USD/EUR Currency in radians
atan2() Returns the arc
Conversion tangent of two
variables x and y
150 USD is equivalent to :120 EUR. atanh() Returns the inverse
hyperbolic tangent of
if you have been following along, the script a number
should be fairly easy to understand. It base_convert() Converts a number
begins by defining a constant named from one number
"EXCHANGE_RATE" which surprise, base to another
surprise stores the dollar-to-euro bindec() Converts a binary
exchange rate (assumed here at 1.00 number to a decimal
number
USD to 0.80 EUR). Next, it defines a
ceil() Round a number up
variable named "$dollars" to hold the
to the nearest integer
number of dollars to be converted, and cos() Returns the cosine of
then it performs an arithmetic operation a number
using the * operator, the "$dollars" cosh() Returns the
variable, and the "EXCHANGE_RATE" hyperbolic cosine of a
constant to return the equivalent number number
of euros. This result is then stored in a decbin() Converts a decimal
new variable named "$euros" and printed number to a binary
to the Web page. number
dechex() Converts a decimal
number to a
PHP Math Introduction
hexadecimal number
The math functions can handle values
decoct() Converts a decimal
within the range of integer and float types. number to an octal
number
Installation deg2rad() Converts a degree
The PHP math functions are part of the value to a radian
PHP core. No installation is required to value
use these functions. exp() Calculates the
exponent of e
expm1() Returns exp(x) – 1
floor() Rounds a number octdec() Converts an octal
down to the nearest number to a decimal
integer number
fmod() Returns the pi() Returns the value of
remainder of x/y PI
getrandmax() Returns the largest pow() Returns x raised to
possible value the power of y
returned by rand() rad2deg() Converts a radian
hexdec() Converts a value to a degree
hexadecimal number value
to a decimal number rand() Generates a random
hypot() Calculates the integer
hypotenuse of a right- round() Rounds a floating-
angle triangle point number
intdiv() Performs integer sin() Returns the sine of a
division number
is_finite() Checks whether a sinh() Returns the
value is finite or not hyperbolic sine of a
is_infinite() Checks whether a number
value is infinite or not sqrt() Returns the square
is_nan() Checks whether a root of a number
value is ‘not-a- srand() Seeds the random
number’ number generator
lcg_value() Returns a pseudo tan() Returns the tangent
random number in a of a number
range between 0 and tanh() Returns the
1 hyperbolic tangent of
log() Returns the natural a number
logarithm of a number
log10() Returns the base-10 PHP Predefined Math Constants
logarithm of a number
log1p() Returns Constant Value Descri
log(1+number) ption
max() Returns the highest INF INF The
value in an array, or infinite
the highest value of M_E 2.718281828459 Return
0452354 se
several specified M_EULER 0.577215664901 Return
values 53286061 s Euler
min() Returns the lowest consta
value in an array, or nt
the lowest value of M_LNPI 1.144729885849 Return
40017414 s the
several specified natural
values logarith
mt_getrandmax() Returns the largest m of PI:
possible value log_e(p
i)
returned by mt_rand() M_LN2 0.693147180559 Return
mt_rand() Generates a random 94530942 s the
integer using natural
Mersenne Twister logarith
algorithm m of 2:
log_e 2
mt_srand() Seeds the Mersenne M_LN10 2.302585092994 Return
Twister random 04568402 s the
number generator natural
logarith
m of PHP_ROUND_HA 3 Round
10: LF_EVEN halves
log_e to even
10 number
M_LOG2E 1.442695040888 Return s
9634074 s the PHP_ROUND_HA 4 Round
base-2 LF_ODD halves
logarith to odd
m of E: number
log_2 e s
M_LOG10E 0.434294481903 Return
25182765 s the
base- PHP Constants
10
logarith
m of E: Constants are either identifiers or simple
log_10 names that can be assigned any fixed
e
M_PI 3.141592653589 Return
values. They are similar to a variable
79323846 s Pi except that they can never be changed.
M_PI_2 1.570796326794 Return They remain constant throughout the
89661923 s Pi/2 program and cannot be altered during
M_PI_4 0.785398163397 Return
44830962 s Pi/4 execution. Once a constant is defined, it
M_1_PI 0.318309886183 Return cannot be undefined or redefined.
79067154 s 1/Pi Constant identifiers should be written in
M_2_PI 0.636619772367 Return
58134308 s 2/Pi
upper case following the convention. By
M_SQRTPI 1.772453850905 Return default, a constant is always case-
51602729 s the sensitive, unless mentioned. A constant
square
root of
name must never start with a number. It
PI: always starts with a letter or underscores,
sqrt(pi) followed by letter, numbers or underscore.
M_2_SQRTPI 1.128379167095 Return It should not contain any special
51257390 s
2/squar characters except underscore, as
e root mentioned.
of PI:
2/sqrt(p
i) Creating a PHP Constant
M_SQRT1_2 0.707106781186 Return The define () function in PHP is used to
54752440 s the
square create a constant as shown below:
root of
½: Syntax:
1/sqrt(2
)
M_SQRT2 1.414213562373 Return define(name, value, case_insensitive)
09504880 s the
square
root of
The parameters are as follows:
2:
sqrt(2) name:
M_SQRT3 1.732050807568 Return
87729352 s the
square - The name of the constant.
root of
3: value:
sqrt(3)
PHP_ROUND_HA 1 Round
LF_UP halves - The value to be stored in the constant.
up
PHP_ROUND_HA 2 Round
LF_DOWN halves
down
Example:
case_insensitive:
Example:
<?php
define("WELCOME",
"GeeksforGeeks!!!");
Output:
GeeksforGeeks
Constants vs Variables ceil() Next Higher integer
• A constant, once defined can never be after rounding
undefined but a variable can be easily cos() Cos value of Radian
input
undefined.
cosh() Hyperbolic cosine
decbin() Binary equivalent of
• There is no need to use dollar sign ($) Decimal number
before constants during assignment but dechex() Hex equivalent of
while declaring variables we use a dollar Decimal number
sign. decoct() Octal equivalent of
Decimal number
• A constant can only be defined using a deg2rad() Convert Degree value
define () function and not by any simple to Radian
assignment. exp() Value of e raised to
the power of input
• Constants don’t need to follow any value
variable scoping rules and can be defined expm1() equivalent to
anywhere. ‘exp(arg) – 1’
floor() nearest lower integer
fmod() reminder (modulo) of
PHP Math functions a division
Mathematics (or math ) functions are getrandmax() largest random value
frequently used in our scripts. There are hexdec() Hexadecimal to
PHP math functions to take care of decimal
addition subtraction multiplication and hypot() hypotenuse of a right-
many other mathematical requirements. angle triangle
intdiv() integer quotient of the
We will discuss these math functions and division (PHP7)
try to develop some sample codes on is_finite() Checking legal finite
these to further understand on how to use number
these functions. is_infinite() Checking whether a
value is infinite
Function Description is_nan() Checks whether a
abs() Absolute value of a value is not a number
number lcg_value() pseudo random
acos() Arc Cosine value of number generator
input log() Log value with
acosh() Inverse hyperbolic different Base
cosine of input log10() Log value with Base
asin() Arc Sin value of input 10
asinh() Inverse hyperbolic log1p() Log value with input
sine of input added by 1
atan() Arc tangent value of max() Maximum value from
input array or group
atan2() Arc tangent of two min() Minimum value from
inputs array or group
atanh() Inverse hyperbolic mt_getrandmax() largest possible
tangent value of input random value
base_convert() Convert number from mt_rand() random value
one base to other generator
bindec() Decimal equivalent of mt_srand() Seeds random value
Binary string generator
octdec() Convert Octal to
Decimal Number
PI() Constant value PI() & column in the
M_PI input array
POW() Exponential value of a array_combine() Creates an
Base array by
round() Rounded value of a using the
number elements
rand() Generates a random from one
integer “keys” array
random_init() cryptographic random and one
integer generator “values”
(PHP 7) array
rad2deg() Convert radian to array_count_values() Counts all
degree the values of
sin() Sin value of Radian an array
input array_diff() Compare
sinh() Hyperbolic sine value arrays, and
sqrt() square root of number returns the
tan() Tangent value of differences
Radian input (compare
tanh() Hyperbolic tangent values only)
value array_diff_assoc() Compare
arrays, and
returns the
PHP ARRAY INTRODUCTION differences
(compare
The array functions allow you to access keys and
and manipulate arrays. values)
Simple and multi-dimensional arrays are array_diff_key() Compare
supported. arrays and
returns the
differences
Installation (compare
The array functions are part of the PHP keys only)
core. There is no installation needed to array_diff_uassoc() Compare
use these functions. arrays, and
returns the
differences
PHP Array Functions
(compare
keys and
Function Description values, using
array() Creates an a user-
array defined key
array_change_key_ca Changes all comparison
se() keys in an function)
array to array_diff_ukey() Compare
lowercase or arrays, and
uppercase returns the
array_chunk() Splits an differences
array into (compare
chunks of keys only,
arrays using a user-
array_column() Returns the defined key
values from a comparison
single function)
array_fill() Fills an array defined key
with values comparison
array_fill_keys() Fills an array function)
with values, array_key_exists() Checks if the
specifying specified key
keys exists in the
array_filter() Filters the array
values of an array_keys() Returns all
array using a the keys of
callback an array
function array_map() Sends each
array_flip() Flips/Exchan value of an
ges all keys array to a
with their user-made
associated function,
values in an which returns
array new values
array_intersect() Compare array_merge() Merges one
arrays, and or more
returns the arrays into
matches one array
(compare array_merge_recursiv Merges one
values only) e() or more
array_intersect_assoc Compare arrays into
() arrays and one array
returns the recursively
matches array_multisort() Sorts multiple
(compare or multi-
keys and dimensional
values) arrays
array_intersect_key() Compare array_pad() Inserts a
arrays, and specified
returns the number of
matches items, with a
(compare specified
keys only) value, to an
array_intersect_uasso Compare array
c() arrays, and array_pop() Deletes the
returns the last element
matches of an array
(compare array_product() Calculates
keys and the product
values, using of the values
a user- in an array
defined key array_push() Inserts one
comparison or more
function) elements to
array_intersect_ukey() Compare the end of an
arrays, and array
returns the array_rand() Returns one
matches or more
(compare random keys
keys only, from an array
using a user-
array_reduce() Returns an (compare
array as a values only,
string, using using a user-
a user- defined key
defined comparison
function function)
array_replace() Returns the array_udiff_assoc() Compare
values of the arrays, and
first array returns the
with the differences
values from (compare
following keys and
arrays values, using
array_replace_recursi Replaces the a built-in
ve() values of the function to
first array compare the
with the keys and a
values from user-defined
following function to
arrays compare the
recursively values)
array_reverse() Returns an array_udiff_uassoc() Compare
array in the arrays, and
reverse order returns the
array_search() Searches an differences
array for a (compare
given value keys and
and returns values, using
the key two user-
array_shift() Removes the defined key
first element comparison
from an functions)
array, and array_uintersect() Compare
returns the arrays, and
value of the returns the
removed matches
element (compare
array_slice() Returns values only,
selected using a user-
parts of an defined key
array comparison
array_splice() Removes function)
and replaces array_uintersect_asso Compare
specified c() arrays, and
elements of returns the
an array matches
array_sum() Returns the (compare
sum of the keys and
values in an values, using
array a built-in
array_udiff() Compare function to
arrays, and compare the
returns the values)
differences
array_unintersect_uas Compare elements in
soc() arrays, and an array
returns the current() Returns the
matches current
(compare element in an
keys and array
values, using each() Deprecated
two user- from PHP
defined key 7.2. Returns
comparison the current
functions) key and
array_unique() Removes value pair
duplicate from an array
values from end() Sets the
an array internal
array_unshift() Adds one or pointer of an
more array to its
elements to last element
the beginning extract() Imports
of an array variables into
array_values() Returns all the current
the values of symbol table
an array from an array
array_walk() Applies a in_array() Checks if a
user function specified
to every value exists
member of in an array
an array key() Fetches a
array_walk_recursivel Applies a key from an
y() user function array
recursively to krsort() Sorts an
every associative
member of array in
an array descending
arsort() Sorts an order,
associative according to
array in the key
descending ksort() Sorts an
order, associative
according to array in
the value ascending
asort() Sorts an order,
associative according to
array in the key
ascending list() Assigns
order, variables as
according to if they were
the value an array
compact() Create array natcasesort() Sorts an
containing array using a
variables and case
their values insensitive
count() Returns the “natural
number of
order” user-defined
algorithm comparison
natsort() Sorts an function
array using a
“natural PHP String Functions
order”
algorithm
In this chapter we will look at some
next() Advance the
internal array commonly used functions to manipulate
pointer of an strings.
array
pos() Alias of strlen()
current()
prev() Rewinds the – Return the Length of a String
internal array - The PHP strlen() function returns the
pointer length of a string.
range() Creates an
array Example
containing a
range of Return the length of the string "Hello
elements world!":
reset() Sets the
internal
<?php
pointer of an
array to its echo strlen("Hello world!"); // outputs
first element 12
rsort() Sorts an ?>
indexed array
in Output:
descending
order
shuffle() Shuffles an
array
sizeof() Alias of
count() str_word_count()
sort() Sorts an
indexed array - Count Words in a String
in ascending
order
The PHP str_word_count() function
uasort() Sorts an
counts the number of words in a string.
array by
values using
a user- Example
defined
comparison Return the length of the string "Hello
function world!":
uksort() Sorts an
array by keys <?php
using a user- echo strlen("Hello world!"); // outputs
defined 12
comparison ?>
function
usort() Sorts an Output:
array using a
Tip: The first character position in a string
is 0 (not 1).
strrev() str_replace()
The PHP strrev() function reverses a The PHP str_replace() function replaces
string. some characters with some other
characters in a string.
Example
Example
Reverse the string "Hello world!":
Replace the text "world" with "Dolly":
<?php
echo strrev("Hello world!"); // outputs <?php
!dlrow olleH echo str_replace("world", "Dolly",
?> "Hello world!"); // outputs Hello
Dolly!
Output: ?>
Output:
strpos()
m
Get a Time
- Represents a month (01 to 12) Here are some characters that are
commonly used for times:
Y
H
- Represents a year (in four digits)
- 24-hour format of an hour (00 to 23)
l (lowercase ‘L’)
h
- Represents the day of the week
- 12-hour format of an hour with leading
Other characters, like"/", ".", or "-" can zeros (01 to 12)
also be inserted between the characters to
add additional formatting. i
The example below formats today's - Minutes with leading zeros (00 to 59)
date in three different ways:
s
Example
- Seconds with leading zeros (00 to 59)
<?php
echo "Today is " . date("Y/m/d") . a
"<br>";
echo "Today is " . date("Y.m.d") . - Lowercase Ante meridiem and Post
"<br>"; meridiem (am or pm)
echo "Today is " . date("Y-m-d") .
"<br>"; The example below outputs the current
echo "Today is " . date("l"); time in the specified format:
?>
Example
Output:
<?php
echo "The time is " . date("h:i:sa");
?>
Output: Example
<?php
$d=mktime(11, 14, 54, 8, 12, 2014);
echo "Created date is " . date("Y-m-d
Get Your Time Zone h:i:sa", $d);
If the time you got back from the code is ?>
not correct, it's probably because your
server is in another country or set up for a Output:
different timezone.
<?php Syntax
date_default_timezone_set("America/N
ew_York"); strtotime(time, now)
echo "The time is " . date("h:i:sa");
?> The example below creates a date and
time from the strtotime() function:
Output:
Example
<?php
$d=strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d
Create a Data With mktime()
h:i:sa", $d);
The optional timestamp parameter in the
?>
date () function specifies a timestamp. If
omitted, the current date and time will be
Output:
used (as in the examples above).
<?php
$lamborghinis = array("Urus",
"Huracan", "Aventador");
The example below outputs the number
echo "Size of the array is: ".
of days until 4th of July:
sizeof($lamborghinis);
$lamborghinis = array("Urus",
?> "Huracan", "Aventador");
Output: <?php
$lamborghinis = array("Urus",
Array "Huracan", "Aventador");
print_r($merged); print_r($merged);
?> ?>
Output: Output:
Array ( Array (
[Suzuki] => Baleno [0] => Baleno
[Skoda] => Fabia [1] => Fabia
[Hyundai] => i20 [2] => i20
[Tata] => Tigor [3] => Tigor
[0] => Vinod [4] => Vinod
[1] => Javed [5] => Javed
[2] => Navjot [6] => Navjot
[3] => Samuel [7] => Samuel
) )
array_values($arr) array_keys($arr)
- In an array, data is stored in form of key- Just like values, we can also extract just
value pairs, where key can be numerical the keys from an array. Let's use this
(in case of indexed array) or user- function to extract the keys from the array
defined strings (in case of associative $merged.
array) and values.
<?php
- If we want to take all the values from our //getting only the keys
array, without the keys, and store them in $keys = array_values($merged);
array_push($lamborghinis, "Estoque");
print_r($keys);
?> print_r($lamborghinis);
?>
Output:
Output:
Array (
[0] => Suzuki Array (
[1] => Skoda [0] => Urus
[2] => Hyundai [1] => Huracan
[3] => Tata [2] => Aventador
[4] => 0 [3] => Estoque
[5] => 1 )
[6] => 2
[7] => 3 array_shift($arr)
)
- This function can be used to remove/shift
array_pop($arr) the first element out of the array. So, it is
just like array_pop() function but different
- This function removes the last element of in terms of the position of the element
the array. Hence it can be used to remove removed.
one element from the end.
<?php
<?php $lamborghinis = array("Urus",
$lamborghinis = array("Urus", "Huracan", "Aventador");
"Huracan", "Aventador");
// removing the first element
// removing the last element array_shift($lamborghinis);
array_pop($lamborghinis);
print_r($lamborghinis);
print_r($lamborghinis); ?>
?>
Output:
Output:
Array (
Array ( [0] => Huracan
[0] => Urus [1] => Aventador
[1] => Huracan )
)
Similar to this, we have another function
array_push($arr, $val) array_unshift($arr, $val) to add a new
value($val) at the start of the array(as the
- This function is the opposite of the first element).
array_pop() function. This can be used to
add a new element at the end of the array. sort($arr)
<?php Array (
function addOne($val) { [Baleno] => Suzuki
// adding 1 to input value [Fabia] => Skoda
return ($val + 1); [i20] => Hyundai
} [Tigor] => Tata
)
$numbers = array(10, 20, 30, 40, 50);
array_reverse($arr)
// using array_map to operate on all the
values stored in array - This function is used to reverse the order
of elements, making the first element last
and last element first, and similarly array_slice($arr, $offset, $length)
rearranging other array elements.
- This function is used to create a subset
<?php of any array. Using this function, we define
$num = array(10, 20, 30, 40, 50); the starting point ($offset, which is the
// printing the array after reversing it array index from where the subset
print_r(array_reverse($num)); starts) and the length (or, the number of
?> elements required in the subset,
starting from the offset).
Output:
- Let's take an example,
Array (
[0] => 50 <?php
[1] => 40 $colors = array("red", "black", "blue",
[2] => 30 "green", "white", "yellow");
[3] => 20
[4] => 10 print_r(array_slice($colors, 2, 3));
) ?>
array_rand($arr) Output:
\n
\r
Example <?php
$my_str = 'You can do anything, but
<?php not everything.';
$my_str = 'If the facts do not fit the
theory, change the facts.'; // Display reversed string
echo strrev($my_str);
// Display replaced string ?>
echo str_replace("facts", "truth",
$my_str); The output of the above code will be:
?>
Output:
The output of the above code will be:
.gnihtyreve ton tub ,gnihtyna od nac uoY
Output:
PHP Date Function
If the truth do not fit the theory, change the
PHP date function is an in-built function
truth.
that simplify working with date data types.
The PHP date function is used to format
You can optionally pass the fourth
a date or time into a human readable
argument to the str_replace() function to
format. It can be used to display the date
know how many times the string
of article was published. record the last
replacements was performed, like this.
updated a data in a database.
Example
In this tutorial, you will learn-
• PHP Date Syntax & Example
<?php
• What is a TimeStamp?
$my_str = 'If the facts do not fit the
• Getting a list of available time zone
theory, change the facts.';
identifiers
• PHP set Timezone Programmatically
// Perform string replacement
• PHP Mktime Function
str_replace("facts", "truth", $my_str,
• PHP Date function
$count);
• Time parameters
• Day parameters
// Display number of replacements
• Month Parameters
performed
• Year Parameters
PHP Date Syntax & Example The value returned by the time function
PHP Date the following basic syntax depends on the default time zone.
- is the general format which we want our Assuming you saved the file
output to be i.e. timestamp.php in phptuts folder, browse to
the URL
o “Y-m-d” http://localhost/phptuts/timestamp.php
o “Y”
o “[timestamp]”
- iterates through the numeric array and - is the time zone identifier
prints the values.
The script below displays the time
Assuming you saved the file according to the default time zone set in
list_time_zones.php in phptuts folder, php.ini.
browse to the URL It then changes the default time zone to
http://localhost/phptuts/list_time_zones Asia/Calcutta and displays the time again.
.php
<?php
Output: echo "The time in " .
date_default_timezone_get() . " is " .
date("H:i:s");
date_default_timezone_set("Asia/Calcu
tta");
echo "The time in " .
date_default_timezone_get() . " is " .
date("H:i:s");
?>
Output:
PHP set Timezone Programmatically
The date_default_timezone_set function
allows you to set the default time zone
from a PHP script.
define () functions.
used to declare constants. A constant can
only be assigned a scalar value, like a
string or a number. A constant’s value
cannot be changed.
define(‘NAME’,’value’);
Parameter Description Example
“L” Returns 1 if it’s <?php
a leap year echo You can separate your PHP file and
and 0 if it is date("L") embed it to your html by using PHP
not a leap year ; include functions.
?>
“Y” Returns four <?php Include functions Description
digit year echo include Includes and
format date("Y") evaluates the
; specified file.
?> Generate a
“y” Returns two <?php warning on failure
(2) digits year echo message if file not
format (00 to date("y") found.
99) ; require Performs the same
?> way as the include
function. Generate
Output: a fatal error
message if file not
found stopping the
script
include_once Same as include
function except it
includes the file
Summary only once.
• The date function is used to format the require_once Same as require
function except it
timestamp into a human desired format.
includes the file
only once.
• The timestamp is the number of seconds
between the current time and 1 st Most of the developers used include
January 1970 00:00:00 GMT. It is also functions for their header and footer. Also,
known as the UNIX timestamp. some use this to write their database
connection and so on.
• All date functions use the default time
zone set in the php.ini file You may write the file with an extension
name of .inc rather than .php to serve as a
• The default time zone can also be set fragment of your program code.
programmatically using PHP scripts.
In some scripts, a file might be included
more than once, causing function
redefinitions, variable reassignments, and number_format () function
other possible problems.
- Format a number with grouped thousand
Syntax: - syntax
string number_format (
include(“filename.inc”); float $number
include_once(“filename.inc”); [, int $decimals = 0 ] )
require(“filename.inc”);
require_once(“filename.inc”); string number_format (
float $number ,
MATHEMATICAL FUNCTION: int $decimals = 0 ,
string $dec_point = '.' ,
string $thousands_sep = ',' )
rand () function
unset function
- used to generate random integers
- syntax
- destroys the specified variable
int rand(void)
- syntax:
int rand(int $min, int $max)
void unset ( mixed $var [, mixed
$... ] )
ceil () function.
explode function.
- returns the next highest integer by
rounding the value upwards
- split a string by string
- syntax
- syntax:
float ceil(float $value)
array explode ( string $delimiter
, string $string [, int $limit ] )
floor () function
implode function.
- returns the next lowest integer by
rounding the value downwards
- join array elements to form a string
- syntax
- syntax:
float floor(float $value)
string implode ( string $glue ,
array $pieces )
min () function
string implode ( array $pieces )
- Return the smallest value
strlen function
- syntax
mixed min(array $values) mixed
- return the value length of a string
min(mixed $values1, mixed
- syntax:
$values2[,mixed $...])
int strlen (string $string)
max () function
strpos function
- Return the highest value
- find the position of the first occurrence of
- syntax
a substring in a given string
mixed max(array $values) mixed
- syntax:
max(mixed $values1, mixed
int strpos ( string $haystack ,
$values2[,mixed $...])
mixed $needle [, int $offset = 0
])
strrev function - syntax:
string ltrim ( string $str [, string
- reverse a given string $charlist ] )
- syntax:
string strrev ( string $string ) rtrim () function
- converts string to uppercase - strip HTML and PHP tags from a string.
- syntax: - syntax:
string strtoupper ( string $str ) string strip_tags ( string $str [,
string $allowable_tags ] )
substr function
DATE MANIPULATION
- returns part of a given string
- syntax:
date () Function
string substr ( string $string ,
int $start [, int $length ] )
- used to format a local time or date
- returns a string formatted according to
ucfirst () function
the given format string.
- syntax:
- Make a string’s first character uppercase
string date ( string $format [, int
- syntax:
$timestamp = time() ] )
string ucfirst( string $str )
Format Description Example
ucwords () function character returned
values
- converts string to uppercase DAY
d Day of the month, 2 01 to 31
- syntax: digits with leading zeros
string ucwords ( string $str ) D A textual representation Mon
of a day, three letters through
Sun
trim () function
j Day of the month 1 to 31
without leading zeros
- stripped white spaces or other characters l A full textual Sunday
from the beginning and end of a string. representation of the through
day of the week Saturday
N ISO-8601 numeric 1 (for
- syntax: representation of the Monday)
string trim ( string $str [, string day of the week (added through 7
in PHP 5.1.0) (for
$charlist ] ) Sunday)
S English ordinal suffix for st, nd, rd
ltrim () function the day of the month, 2 or th.
characters Works
well with j
- strip white spaces or other characters w Numeric representation 0 (for
from the beginning of a string. of the day of the week Sunday)
through 6 B Swatch Internet time 000 through
(for 999
Saturday) g 12-hour format of an 1 through 12
z The day of the year 0 through hour without leading
(starting from 0) 365 zeros
W ISO-8601 week number Example: G 24-hour format of an 0 through 23
of year, weeks starting 42 (the hour without leading
on Monday 42nd week zeros
in the h 12-hour format of an 01 through12
year) hour with leading
zeros
Format Description Example H 24-hour format of an 00 through 23
character returned hour with leading
values zeros
MONTH i Minutes with leading 00 to 59
F A full textual January zeros
representation of a through s Seconds, with leading 00 through 59
month, such as December zeros
January or March u Microseconds Example:
m Numeric 01 654321
representation of a through
month, with leading 12 Format Description Example
zeros character returned
M A short textual Jan values
representation of a through TIMEZONE
month, three letters Dec e Timezone identifier Examples:
n Numeric 1 through UTC, GMT,
representation of a 12 Atlantic/Azor
month, without leading es
zeros I Whether or not the 1 if Daylight
t Number of days in the 28 date is in daylight Saving Time,
given month through saving time 0 otherwise.
31 O Difference to Example:
Greenwich time +0200
Format Description Example (GMT) in hours
character returned P Difference to Example:
values Greenwich time +02:00
YEAR (GMT) with colon
L Whether it’s a leap year 1 if it is a between hours and
leap year, minutes
0 T Timezone Example:
otherwise. abbreviation EST, MDT…
o ISO-8601 year number. Examples: z Timezone offset in -43200
This has the same value 1999 or seconds. The offset through
as Y, except that if the 2003 for timezones west of 50400
ISO week number (W) UTC is always
belongs to the previous negative, and for
or next year, that year is those east of UTC is
used instead. always positive.
Y A full numeric Examples:
representation of a year, 1999 or
4 digits 2003 Format Description Example
y A two digit representation Examples: charact returned values
of a year 99 or 03
er
FULL DATE/TIME
Format Description Example
character returned c ISO 8601 2004-02-
values date 12T15:19:21+00
TIME :00)
a Lowercase Ante am or pm r >> RFC Example: Thu,
meridiem and Post 2822 21 Dec 2000
meridiem
A Uppercase Ante AM or PM formatted 16:01:07 + 0200
meridiem and Post date
meridiem
U Seconds See also time ()
since the - parse any English textual datetime
Unix Epoch description into a Unix timestamp
(January 1, - syntax:
1970, int strtotime ( string $time
00:00:00 [, int $now = time() ] )
GMT)
what is the function name inside of the 6.) Function can have a return value.
code?
A. False
A. 1 B. True
B. value
C. one 7.) Syntax for foreach
D. $t
A. foreach($arr){}
2.) it is required to create a function name B. foreach{}($arr as $value)
for a function C. foreach($value){}
D. foreach($arr as $value){}
A. False
B. True 8.) $g = 200;
function a(){echo “5”;}
3.) Function count($val){ function b(){echo “4”}
$c = 0; ab();
$c += $val;
echo $c; what is the output of the code?
}
count(10); A. 54
count(5); B. 200
C. error
What is the output of the code? D. 45
What is the value of index 0? 10.) Using foreach statement you can
display both the keys and value of each
A. grape element in the array.
B. orange
C. banana A. True
B. False 16.) $t = 100;
function one(){
11.) rsort(), arsort(), and krsort() functions echo “1000”;
are used to sort elements in the array in }
descending order. one();
A. grape
B. orange
34.) Local Variables is one that declared 40.) $num=array(1,2,3,4,5,):
outside a function and is available to all foreach(num as $val){
parts of the program. echo $val
}
A. False – Global Variables
B. True Check the code if valid or invalid?
A. True A. a
B. False B. B
C. $a
38.) var_dump function is same as print_r D. $b
function except it adds additional
information about the data of each 43.) function disp(){
element. function disp2(){
echo “hello”;
A. False }
B. True }
disp();
39.) is a group of PHP statements that disp2();
performs a specific task. Functions are
designed to allow you to reuse the same A. hello
code in different locations. B. blank
C. error
A. Operations D. disp
B. Variables
C. Functions 44.) Array can be used as ordinary array
D. Arrays same as in C and C++ arrays.
A. False
B. True
47.) functions are commonly used for 53.) prints additional information about the
debugging. The point of this of these size and type of the values it discovers
functions is to help you visualize what’s
going on with compound data structures A. var_add()
like arrays. B. var_size()
C. var_info()
A. print_a() and var_size() D. var_dump()
B. print_p() and var_add()
C. print_r() and var_dump() 54.) $a[] = “mango”;
D. print_c() and var_info() $a[] = “apple”;
$a[] = “banana”;
48.) function is used to print the array
structure. Check the code if valid or invalid?
A. print_s A. Valid
B. print_a B. Invalid
C. print_r
D. print_f 55.) Function count($val){
static $c = 0;
49.) is declared inside a function and is $c += $val;
only available within the function in which echo $c;
it is declared. }
Count(4);
A. Global variables Count(3);
B. Dynamic variables
C. Local variables What is the output of the code?
D. Static variables
A. 43
50.) This takes an argument of any type B. Error – count(4) count(3)
and prints it out, which includes printing all C. 47
its parts recursively. D. 7
FORMATIVE 4 A. False
B. True
1.) function is used to print the array
structure 7.) is used to aggregate a series of similar
items together, arranging and
A. print_s dereferencing them in some specific way.
B. print_f
C. print_r A. Variable
B. Index B. val
C. Array C. $value
D. Function D. value$
8.) Function count($val){ 13.) You can insert CSS code inside of a
$c = 0; function.
$c += $val;
echo $c; A. False
} B. True
count(10);
count(5); 14.) Array index in PHP can be also called
as array storage.
What is the output of the code?
A. False – Array keys
A. Error B. True
B. 5
C. 15 15.) Sorts by key
D. 105
A. usort($array)
9.) Function count($val){ B. kusort($array)
static $c = 0; C. ksort($array)
$c += $val; D. krsort($array)
echo $c;
} 16.) used to generate random integers
count(4);
count(3); A. ran()
B. rand()
What is the output of the code? C. random()
D. rndm()
A. 43
B. error 17.) Format character for ISO-8601
C. 47 numeric representation of the day of the
D. 7 week (added in PHP 5.1.0)
A. val$
19.) Format character for a full textual D. array explode (int $delimiter, int $string
representation of the month, such as [, int $limit ] )
January or March
25.) $x = max(10, 5, 3, 20); echo $x;
A. J
B. M What is the output?
C. F
D. T A. 20
B. 5
20.) String number_format( C. 10
float $number, D. 3
int _____;
} 26.) Format character for day of the month
without leading zeros
A. $points
B. $thousands_sep A. j
C. $decimals B. z
D. $dec_points C. m
D. d
21.) Syntax for require once
27.) There will be a warning text if the
A. require_once(filename.php); include file not found.
B. require_once(“filename.inc”);
C. require_once(filename.inc); A. False
D. filename(“require_once”); B. True
22.) In some scripts, a file might be 28.) Syntax to strip white spaces or other
included more than once, causing function characters form the end of a string.
redefinitions, variable reassignments, and
other possible problems. A. string strim(string $str [, string $charlist
])
A. False B. string btrim(string $str [ , string
B. True $charlist])
C. string ctrim(string $str [, string $chalist
23.) Format character for number of days ])
in the given month D. string rtrim(string $str [, string
$charlist ] )
A. m
B. t 29.) Number format can show or hide the
C. d decimal places.
D. n
A. True
24.) Syntax for explode. B. False
A. array explode (string $delimiter, 30.) Format character for a full number
string $string, [, int $limit ] ) representation of a year, 4 digits
B. array explode (int $delimiter, string
$string [, int $limit ] ) A. y
C. array explode (string $delimiter, string B. c
$string [, string $limit ] ) C. Y
D> r
38.) function disp(){
31.) sort() and rsort() does not maintain its function disp2(){
index reference for each values. echo “hello”;
}
A. False }
B. True Disp();
disp2();
32.) You use can functions in different
ways. A. error
B. blank
A. True C. hello
B. False D. disp
33.) Function can only do something 39.) Sorts by value; keeps the same key.
without passing values.
A. rsort($array)
A. True B. asort($array)
B. False C. arsort($array)
D. sort($array)
34.) rsort(), arsort(), krsort() functions are
used to sort elements in the array in 40.) Syntax of a function
descending order.
A. Param_function
A. False B. Function name(param){}
B. True C. Function name {param}
D. Param (function name){}
35.) it is required to create a function
name for a function 41.) function keyword is used in PHP to
declare a function.
A. False
B. True A. True
B. False
36.) The foreach statement is used to
iterate through the element in an array. 42.) specify an array expression within a
set of parenthesis following the foreach
A. True keyword.
B. False
A. False
37.) PHP has a built-in function to perform B. True
operations.
43.) $g = 200;
A. True function a(){echo “5”;}
B. False function b(){echo “4”;}
a();
A. 4
B. 5
C. 200
D. Error
50.) used to declare constants
44.) $x = floor(5.2); echo $x;
A. function
What is the output? B. define
C. derive
A. Blank D. set
B. 6
C. Error 51.) Format character for a short textual
D. 5 representation of a month, three letters
A. Titles
B. Footer
C. Body
D. Content