Nothing Special   »   [go: up one dir, main page]

Applications Development and Emerging Technologies Reviewer

Download as pdf or txt
Download as pdf or txt
You are on page 1of 87

APPLICATIONS DEVELOPMENT AND EMERGING

TECHNOLOGIES REVIEWER
MODULE 3
PHP Arrays and User Defined
Functions

PHP Arrays

Array

- is used to aggregate a series of similar


items together, arranging and Example 2: Code 2
dereferencing them in some specific way.
<?php
• Each member of the array index $fruit[] = "orange";
references a corresponding value and can $fruit[] = "apple";
be a simple numerical reference to the $fruit[] = "grapes";
value’s position in the series, or it could $fruit[] = "banana";
have some direct correlation to the value. echo "<pre>";
print_r($fruit);
• PHP array does not need to declare how
echo "</pre>";
many elements that the array variable
?>
have.

• Array index in PHP can be also called as


array keys.

• Array can be used as ordinary array


same as in C and C++ arrays.

ARRAY

one dimensional Example: Code 3

Example: Code 1 <?php


$fruit = array("orange",
<?php "apple", "grapes", "banana");
$fruit[0] = "orange"; echo "<pre>";
$fruit[1] = "apple"; print_r($fruit);
$fruit[2] = "grapes"; echo "</pre>";
$fruit[3] = "banana"; ?>
echo "<pre>";
print_r($fruit);
echo "</pre>";
?>
Output:

Output:

Example: using var_dump ()

$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.

var_dump() function - is same as the


print_r function except that it prints
additional information about the size and
type of the values it discovers

print_r() and var_dump() functions are


commonly used for debugging. The point
of this of these functions is to help you Output:
visualize what’s going on with compound
data structures like arrays.

Example: using print_r ()

<?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.

foreach statement - specify an array


expression within a set of parenthesis
following the foreach keyword.
Syntax
Output:
foreach($arr as $value){
//do something with $value
variable
}
foreach($arr as $key => $value){
//do something with $key
and/or $value variable Example:
}
<?php
$person = array(
'First Name' => 'Juan',
'Last Name' => 'Dela Cruz',
'Date of Birth' => 'April 3,
1986',
'Gender' => 'Male'
$arr - The name of the array that you’re );
walking through.
$key - The name of the variable where foreach($person as $value){
you want to store the key. (optional) echo "$value <br/>";
$value - The name of the variable where }
you want to store the value. echo "<p/>";
foreach($person as $key =>
Example: $value){
echo "$key: $value <br/>";
<?php }
$fruit = array( ?>
"orange",
"apple",
"grapes",
"banana",
"dragon fruit");
foreach($fruit as $value){
echo "$value<br/>";
}
?>
}
}
Output: ?>

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.

User defined functions

- functions that are provided by the user of


the program.

Predefined functions

- functions that are built-in into PHP to


perform some standard operations
footer();
FUNCTIONS ?>

User defined functions


Syntax

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.

Function with no parameters


Function with parameters
Example:
Example:
<?php
function redline(){ <?php
?> function hrline($height,
<hr style=" $color){
background-color: #f00; ?>
height: 5px; <hr
"/> style="
<?php height:<?php echo
} $height; ?>;
background-color:
function footer(){ <?php echo $color?>"
echo "PHP Test Page &copy />
2013"; <?php
}
}
echo "First Text";
redline(); echo "First Text";
echo "Second Text"; hrline("5px", "#00f");
redline(); echo "second Text";
hrline("10px", "#0f0");
?>

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.

Static Variables - is used to retain the


values calls to the same function.

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 />";

Value is 1 /* Second method to create array. */


Value is 2 $salaries['mohammad'] = "high";
Value is 3 $salaries['qadir'] = "medium";
Value is 4 $salaries['zara'] = "low";
Value is 5
Value is one echo "Salary of mohammad is ".
Value is two $salaries['mohammad'] .
Value is three "<br />";
Value is four echo "Salary of qadir is ".
Value is five $salaries['qadir']. "<br />";
echo "Salary of zara is ".
Associative Arrays $salaries['zara']. "<br />";
The associative arrays are very similar to ?>
numeric arrays in term of functionality, but
they are different in terms of their index. </body>
Associative array will have their index as </html>
string so that you can establish a strong
association between key and values. This will produce the following result –

To store the salaries of employees in an Output:


array, a numerically indexed array would
not be the best choice. Instead, we could Salary of mohammad is 2000
use the employees names as the keys in Salary of qadir is 1000
our associative array, and the value would Salary of zara is 500
be their respective salary. Salary of mohammad is high
Salary of qadir is medium
NOTE - Don't keep associative array Salary of zara is low
inside double quote while printing
otherwise it would not return any value. Multidimensional Arrays
A multi-dimensional array each element in
Example the main array can also be an array. And
each element in the sub-array can be an
<html> array, and so on. Values in the multi-
<body> dimensional array are accessed using
multiple index.
<?php
/* First method to associate create Example
array. */
$salaries = array("mohammad" => In this example we create a two-
2000, "qadir" => 1000, dimensional array to store marks of three
"zara" => 500); students in three subjects –
This example is an associative array, you Marks for qadir in maths : 32
can create numeric array in the same Marks for zara in chemistry : 39
fashion.
ARRAYS
<html>
<body>
Array
<?php • An array is an ordered collection of
$marks = array( elements. Each element has a value and
"mohammad" => array ( is identified by a key. Each array has its
"physics" => 35, own unique keys.
"maths" => 30,
"chemistry" => 39 • The keys can be either integer numbers
), or strings.

"qadir" => array ( The array() Construct


"physics" => 30, • Calling The array () construct creates a
"maths" => 32, new array. Passing a series of values to
"chemistry" => 29 the array () construct will populate the
), new created array with these values.

"zara" => array ( • Each one of the values will automatically


"physics" => 31, get an index number, that will be its key.
"maths" => 22,
"chemistry" => 39 • We can alternatively specify both the
) keys and the values.
);
Examples:
/* Accessing multi-dimensional array
values */ <?php
echo "Marks for mohammad in $vec_1 = array(2,4,5);
physics : " ; echo "<BR><BR>"."simple array of
echo $marks['mohammad']['physics'] . numbers";
"<br />"; for($i=0; $i<3; $i++)
{
echo "Marks for qadir in maths : "; echo "<BR>".$vec_1[$i];
echo $marks['qadir']['maths'] . "<br />"; }
?>
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br Output:
/>";
?>

</body>
</html>

This will produce the following result –

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:

The var_dump() Function


• Prints out the content of a composite
value (e.g., array) together with the data
type of each one of the values.

<?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:

The list() Construct


The print_r() Function • The list() construct provides a short cut
• Prints out the contents of a composite for an automatic assignment of an array's
value (e.g., array). elements into individual variables.
• Unlike var_dump(), this function cannot
print out more than one array. <?php
$info = array('moshe', 'david',
<?php 'michael','john');
class Rectangle {} list($operation_manager,
$vec_1 = array(2,4,5,123,”fofo”,new $marketing_manager,
Rectangle()); ,$finance_manager) = $info;
print_r($vec_1); echo "<BR>operation department
?> manager is $operation_manager";
echo "<BR>finance department
Output: manager is $finance_manager";
echo "<BR>marketing department
manager is $marketing_manager";
?>

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

• As of PHP 5.5 we can use the list The Output:


construct together with the foreach loop.

<?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:

1. The two arrays contain the same


elements. The count () Function
2. The two arrays have their identical Calling the count () function on a given
elements in the same position array returns its size.

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.

<?php The array_key_exists () function does


$vec = array('a'=>1,'b'=>2,'c'=>3); return true in those cases.
if(isset($vec['a'])) echo "<BR>'a' key
exists"; The array_flip () Function
if(isset($vec['b'])) echo "<BR>'b' key This function returns a new array, which is
exists"; the result of inverting value of each
if(isset($vec['c'])) echo "<BR>'c' key element with its key.
exists";
if(isset($vec['d'])) echo "<BR>'d' key <?php
exists"; $vec_1 =
if(isset($vec['e'])) echo "<BR>'e' key array("a","b","c","d","f","g","h");
exists"; echo "<BR>before...<BR>";
?> var_dump($vec_1);
$vec_2 = array_flip($vec_1);
Output: echo "<BR>after...<BR>";
var_dump($vec_2);
?>

Output:

The array_key_exists() Function


Calling the array_key_exists() function
can tell us if a specific key already exists
in our array... or not.

<?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:

The Array Pointer The foreach Construct


When going over the elements, there is a The foreach construct allows traversing an
pointer that points at the current element. array from start.

reset () to finish.

- resets the pointer to the array initial foreach (___ as ___ => ___)
position. {

next () …

- moves the pointer to the next element. }

prev () variable to hold element’s value.


variable to hold element’s key.
- moves the pointer to the previous code
element.
foreach($vec as $value_var)
{
echo "<BR>$value_var";
}
?>

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:


}

variable that holds the array


variable to hold element’s value.
code

The array_walk () Function


The array_walk (array &$vec, callback
$function) function goes over each one
of the array's elements and calls the
function on each one of them.
<?php
$vec =
array('moshe','david','michael','mike');
The function should include two $japan_cars = array("T" => "Toyota",
parameters. The first is the array's value "M" => "Mazda", "S" => "Suzuki", "Y"
and the second is the array's key. => "Yamaha");
$usa_cars = array("C" => "Chevrolet",
The array_walk has a third optional "P" => "Pontiac", "C" =>
parameter ($user_data). If it is passed, "Cryzler");
then it would be passed as an argument to $cars = array("US" => $usa_cars, "JP"
the function that is called on each one of => $japan_cars);
the elements. function changearray(&$val, $key,
$prefix)
<?php {
$cars = array("T" => "Toyota", "M" => $val = "$prefix: $val";
"Mazda", "S" => "Suzuki", "Y" => }
"Yamaha"); function printarray($itemvalue,
function changearray(&$val, $key, $itemkey)
$prefix) {
{ echo "$itemkey : $itemvalue<br>";
$val = "$prefix: $val"; }
} echo "before ...<BR>";
function printarray($itemvalue, array_walk_recursive($cars,
$itemkey) 'printarray');
{ array_walk_recursive($cars,
echo "$itemkey : $itemvalue<br>"; 'changearray', 'car');
} echo "after...<BR>";
echo "before ...<BR>"; array_walk_recursive($cars,
array_walk($cars, 'printarray'); 'printarray');
array_walk($cars, 'changearray', 'car'); ?>
echo "after...<BR>";
array_walk($cars, 'printarray'); Output:
?>

Output:

The array_walk_recursive () Function


The array_walk_recursive does the same
work done by array_walk... with the
following improvement: The
array_walk_recursive goes over all Arrays Sorting
elements of all arrays that are held as PHP core functions include various
elements of the main array. methods for sorting arrays.
The simplest ones are:
<?php
sort (array &$vec [, int $sort_flags ])
asort (array &$vec [, int $sort_flags ])
Calling sort () destroys all keys and
reassign new ones starting from zero.
Calling asort () keeps the keys
unchanged.

<?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

- This is the default. Sorting will be


performed according to elements' values
and without introducing any change.

SORT_NUMERIC

- Each element's value will be first


converted into a numeric value. The
sorting will be according to these numeric
values.

SORT_STRING

- Sorting will be according to the elements'


values converted into strings.

rsort () function

- sorts an array in a reverse order.


- removes all elements' keys and assign
new ones.
function __construct($idVal,
<?php $averageVal, $nameVal)
$vec = array( {
"a"=>"foofoo", $this->id = $idVal;
"b"=>"gondola", $this->average = $averageVal;
"c"=>"israel", $this->name = $nameVal;
"h"=>"honduras", }
"d"=>"greece"); public function getId()
var_dump($vec); {
rsort($vec); return $this->id;
echo "<p>"; }
var_dump($vec); public function getAverage()
?> {
return $this->average;
Output: }
public function getName()
{
return $this->name;
}
public function __toString()
{
return $this->getName () . " id=" . $this-
>getId () .
" average=" . $this->getAverage ();
}
}
$vec = [
new Student ( 123123, 98, "danidin" ),
new Student ( 523434, 88, "moshe" ),
new Student ( 456544, 92, "spiderman"
),
new Student ( 744565, 77, "superman" )
];
echo "<h2>before</h2>";
foreach ( $vec as $k => $v )
{
The ksort () and krsort () functions sort echo "<Br>$k => " . $v;
an array by its elements' keys. }
The usort (array &$vec, callback usort ( $vec, function ($a, $b)
$function) function sorts an array by its {
elements' values and using a user defined echo "<br>comparing between ".$a-
comparison function. >getName()." and ".$b->getName();
return $a->getId() - $b->getId();
<?php } );
class Student echo "<h2>after</h2>";
{ foreach ( $vec as $k => $v )
private $id; {
private $average; echo "<Br>$k => " . $v;
private $name; }
?>
Output:

Array Shuffle
Calling the shuffle () function will
scramble arrays' elements in a randomize
order.

Arrays Randomized Elements

- Using the array_rand(array $input [, int


$num_req ] ) function we can get
randomized selected elements from our
<?php array. The first parameter is our array. The
function cmp($a, $b) second parameter is the number of
{ elements we request.
if ($a == $b) {
return 0; - If we request one element only,
} array_rand() returns the key for the
return ($a < $b) ? -1 : 1; random element. If we request more than
} one element, array_rand() returns an
$vec = array of keys for the random elements.
array(12,532,12,56322343,232,5,2,1,1,1,
4, 2, 5, 6, 1); <?php
usort($vec, "cmp"); $vec =
foreach ($vec as $key => $value) array("a","b","c","d","f","g","h");
{ $random_keys = array_rand($vec,3);
echo "$key: $value<BR>"; echo $vec[$random_keys[0]];
} echo "<BR>";
?> echo $vec[$random_keys[1]];
echo "<BR>";
Output: echo $vec[$random_keys[2]];
echo "<BR>";
?>

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.

array array_intersect (array $array1,


Arrays Shorter Syntax
array $array2 [, array $ ...])
As of PHP 5.4 we can create new arrays
in the following new short syntax:
<?php
$vecA =
$vec = [34,234,75,4];
array("il"=>"israel","ru"=>"russia","fr"=
<?php
>"france","jo"=>"jordan");
$vec_a = [4,6,2,7];
var_dump($vecA);
$vec_b =
echo "<br/>";
['a'=>'australia','b'=>'belgium','c'=>'can
$vecB =
ada'];
array("ill"=>"israel","ru"=>"russia","fr"
foreach($vec_a as $k=>$v)
=>"franc","jo"=>"jordan");
{
var_dump($vecB);
echo " ".$k."=>".$v;
echo "<br/>";
}
$vecC = array_intersect($vecA,$vecB);
foreach($vec_b as $k=>$v)
var_dump($vecC);
{
?>
echo " ".$k."=>".$v;
}
Output:
Output:
Arrays Constants
PHP 5.6 added the possibility to define
array constants using the const keyword.
As of PHP 7 we can define array
constants using the define () function.

<?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

As of PHP 5.5 we can develop a function


that returns an array and use a call to that
function as if it was an array.

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.

This new operator assists us with those


cases in which we need to check whether
the array we work with has a specific key PHP FUNCTIONS
so we could use its value and if not, then
another value will be used instead. The real power of PHP comes from its
functions.
$vec = PHP has more than 1000 built-in
['a'=>'abba','b'=>'baba','m'=>'mama']; functions, and in addition you can create
//before PHP7 your own custom functions.
//$temp =
isset($vec['d'])?$vec['d']:'default'; PHP Built-in Functions
$temp = $vec['d']??'default'; PHP has over 1000 built-in functions
echo "<h1>$temp</h1>"; that can be called directly, from within a
script, to perform a specific task.
Output:
PHP User Defined Functions
Besides the built-in PHP functions, it is
possible to create your own functions.
• A function is a block of statements that PHP Function Arguments
can be used repeatedly in a program. Information can be passed to functions
through arguments. An argument is just
• A function will not execute automatically like a variable.
when a page loads.
Arguments are specified after the function
• A function will be executed by a call to name, inside the parentheses. You can
the function. add as many arguments as you want, just
separate them with a comma.
Create a User Defined Function in PHP
A user-defined function declaration The following example has a function with
starts with the word function: one argument ($fname). When the
familyName () function is called, we also
Syntax pass along a name (e.g., Jani), and the
name is used inside the function, which
function functionName() { outputs several different first names, but
code to be executed; an equal last name:
}
Example
Note: A function name must start with a
letter or an underscore. Function names <?php
are NOT case-sensitive. function familyName($fname) {
echo "$fname Refsnes.<br>";
Tip: Give the function a name that reflects }
what the function does! familyName("Jani");
familyName("Hege");
In the example below, we create a function familyName("Stale");
named "writeMsg ()". The opening curly familyName("Kai Jim");
brace ( { ) indicates the beginning of the familyName("Borge");
function code, and the closing curly brace ?>
( } ) indicates the end of the function. The
function outputs "Hello world!". To call Output:
the function, just write its name followed
by brackets ():

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

<?php declare(strict_types=1); // strict


requirement
function addNumbers(int $a, int $b) {
return $a + $b;
PHP is a Loosely Typed Language }
In the example above, notice that we did echo addNumbers(5, "5 days");
not have to tell PHP which data type the // since strict is enabled and "5 days" is
variable is. not an integer, an error will
be thrown
PHP automatically associates a data type ?>
to the variable, depending on its value.
Since the data types are not set in a strict The strict declaration forces things to be
sense, you can do things like adding a used in the intended way.
string to an integer without causing an
error. PHP Default Argument Value
The following example shows how to use
In PHP 7, type declarations were added. a default parameter. If we call the function
This gives us an option to specify the setHeight() without arguments it takes the
expected data type when declaring a default value as argument:
function, and by adding the strict
declaration, it will throw a "Fatal Error" if Example
the data type mismatches.
<?php declare(strict_types=1); // strict
In the following example we try to send requirement
both a number and a string to the function function setHeight(int $minheight = 50)
without using strict: {
echo "The height is : $minheight
Example <br>";
}
<?php setHeight(350);
function addNumbers(int $a, int $b) { setHeight(); // will use the default value
return $a + $b; of 50
} setHeight(135);
echo addNumbers(5, "5 days"); setHeight(80);
// since strict is NOT enabled "5 days" ?>
is changed to int(5), and it will
return 10
?>

To specify strict we need to set declare


(strict_types=1);. This must be on the
very first line of the PHP file.
Output: function addNumbers(float $a, float $b)
: float {
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>

PHP Functions – Returning values. Output:


To let a function, return a value, use the
return statement:

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:

PHP Return Type Declarations


PHP 7 also supports Type Declarations for
the return statement. Like with the type PHP FUNCTIONS
declaration for function arguments, by
enabling the strict requirement, it will throw PHP functions are similar to other
a "Fatal Error" on a type mismatch. programming languages. A function is a
piece of code which takes one more input
To declare a type for the function return, in the form of parameter and does some
add a colon ( : ) and the type right before processing and returns a value.
the opening curly ( { )bracket when
declaring the function. You already have seen many functions
like fopen () and fread () etc. They are
In the following example we specify the built-in functions, but PHP gives you
return type for the function: option to create your own functions as
well.
Example
There are two parts which should be clear
<?php declare(strict_types=1); // strict to you –
requirement
• Creating a PHP Function This will display following result –
• Calling a PHP Function
Output:
In fact, you hardly need to create your own
PHP function because there are already You are really a nice person, Have a nice
more than 1000 of built-in library time!
functions created for different area and
you just need to call them according to PHP Functions with Parameters
your requirement. PHP gives you option to pass your
parameters inside a function. You can
Please refer to PHP Function Reference pass as many as parameters your like.
for a complete set of useful functions. These parameters work like variables
inside your function. Following example
Creating a PHP Function takes two integer parameters and add
them together and then print them.
Its very easy to create your own PHP
function. Suppose you want to create a <html>
PHP function which will simply write a
simple message on your browser when <head>
you will call it. Following example creates <title>Writing PHP Function with
a function called writeMessage () and Parameters</title>
then calls it just after creating it. </head>

Note that while creating a function its <body>


name should start with keyword function
and all the PHP code should be put inside <?php
{ and } braces as shown in the following function addFunction($num1, $num2) {
example below – $sum = $num1 + $num2;
echo "Sum of the two numbers is :
<html> $sum";
}
<head>
<title>Writing PHP Function</title> addFunction(10, 20);
</head> ?>

<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

/* Calling a PHP Function */


Passing Arguments by Reference
writeMessage();
It is possible to pass arguments to
?>
functions by reference. This means that a
reference to the variable is manipulated by
</body>
the function rather than a copy of the
</html>
variable's value.
PHP Functions returning value.
Any changes made to an argument in A function can return a value using the
these cases will change the value of the return statement in conjunction with a
original variable. You can pass an value or object. return stops the execution
argument by reference by adding an of the function and sends the value back
ampersand to the variable name in either to the calling code.
the function call or the function definition.
You can return more than one value from
Following example depicts both the cases. a function using return array (1,2,3,4).

<html> Following example takes two integer


parameters and add them together and
<head> then returns their sum to the calling
<title>Passing Argument by program. Note that return keyword is
Reference</title> used to return a value from a function.
</head>
<html>
<body>
<head>
<?php <title>Writing PHP Function which
function addFive($num) { returns value</title>
$num += 5; </head>
}
<body>
function addSix(&$num) {
$num += 6; <?php
} function addFunction($num1, $num2) {
$sum = $num1 + $num2;
$orignum = 10; return $sum;
addFive( $orignum ); }
$return_value = addFunction(10, 20);
echo "Original Value is $orignum<br
/>"; echo "Returned value from the
function : $return_value";
addSix( $orignum ); ?>
echo "Original Value is $orignum<br
/>"; </body>
?> </html>

</body> This will display following result –


</html>
Output:
This will display following result –
Returned value from the function : 30
Output:
Setting Default Values for Function
Original Value is 10
Parameters
Original Value is 16
You can set a parameter to have a default
value if the function's caller doesn't pass it.
Following function prints NULL in case
use does not pass any value to this $function_holder = "sayHello";
function. $function_holder();
?>
<html>
</body>
<head> </html>
<title>Writing PHP Function which
returns value</title> This will display following result –
</head>
Output:
<body>
Hello
<?php
function printMe($param = NULL) { STUDY GUIDE
print $param;
} ARRAY

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.

<html> print_r() function

<head> - short for print recursive. This takes an


<title>Dynamic Function Calls</title> argument of any type and prints it out,
</head> which includes printing all its parts
recursively.
<body>
var_dump() function
<?php
function sayHello() { - is same as the print_r function except
echo "Hello<br />"; that it prints additional information about
} the size and type of the values it discovers
$value
print_r() and var_dump() functions are
commonly used for debugging. The point - The name of the variable where you
of this of these functions is to help you want to store the value.
visualize what’s going on with compound
data structures like arrays. Example:

foreach() function <?php


$fruit = array(
- is a statement used to iterate or loop "orange",
through the element in an array. With each "apple",
loop, a foreach statement moves to the "grapes",
next element in an array. "banana",
"dragon fruit");
foreach statement foreach($fruit as $value){
echo "$value<br/>";
- specify an array expression within a set
}
of parenthesis following the foreach
?>
keyword.

Syntax

foreach($arr as $value){
//do something with $value
variable
}
foreach($arr as $key => $value){
//do something with $key
and/or $value variable
}
Output:

Array: Looping through array elements


Example:
$arr
<?php
- The name of the array that you’re $person = array(
walking through. 'First Name' => 'Juan',
'Last Name' => 'Dela Cruz',
$key 'Date of Birth' => 'April 3,
1986',
- The name of the variable where you 'Gender' => 'Male'
want to store the key. (optional) );

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

- is a group of PHP statements that


performs a specific task. Functions are
designed to allow you to reuse the same
code in different locations.

User defined functions

- functions that are provided by the user of


the program.

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:

- is the formal parameters of the function.


Parameter must follow the rule of naming
identifier.

Example without parameter:

<?php Example with parameter:


function redline(){
?> <?php
<hr style=" function hrline($height,
background-color: #f00; $color){
height: 5px; ?>
"/> <hr
<?php style="
} height:<?php echo
$height; ?>;
function footer(){ background-color:
echo "PHP Test Page &copy <?php echo $color?>"
2013"; />
} <?php

echo "First Text"; }


redline();
echo "Second Text"; echo "First Text";
redline(); hrline("5px", "#00f");
footer(); echo "second Text";
?> hrline("10px", "#0f0");
?>

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

include() function (file not found)

Including Files Example:


You can separate your PHP file and
embed it to your html by using PHP <html>
include functions. <head>
<title></title>
Include functions Description <meta http-equiv="Content-
include Includes and Type" content="text/html;
evaluates the charset_UTF-8">
specified file. </head>
Generate a <body>
warning on failure <?php
message if file not
include("somefile.inc")?>
found.
require Performs the same <h4>Content</h4>
way as the include The quick brown fox jumps
function. Generate over the lazy dog near the bank of
a fatal error the rivers
message if file not </body>
found stopping the </html>
script
include_once Same as include
function except it
includes the file
only once.
require_once Same as require
function except it
includes the file
only once. Output:

Most of the developers used include


functions for their header and footer. Also,
some use this to write their database
connection and so on.

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:

In some scripts, a file might be included <html>


more than once, causing function
<head>
<title></title>
<meta http-equiv="Content-
Type" content="text/html;
charset_UTF-8">
</head>
header.inc
<body>
<?php
require("somefile.inc")?>
<h4>Content</h4> Output:
The quick brown fox jumps
over the lazy dog near the bank of
the rivers
</body>
</html>

Same output using require function.

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

- Return the highest value


- syntax

mixed max(array $values) mixed


max(mixed $values1, mixed
$values2[,mixed $...])

rand(), ceil(), floor(), min(), max()

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

MODULE 4 $fruitArr = explode(",",


Array, String and Date Manipulation $fruitStr);
foreach ($fruitArr as
FUNCTION FOR ARRAY $fruit) echo $fruit." ";
MANIPULATION: ?>

unset function

- destroys the specified variable


- syntax:
void unset ( mixed $var [, mixed
$... ] )
Output:
explode function.

- split a string by string


- syntax:
array explode ( string $delimiter
, string $string [, int $limit ] )

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

- reverse a given string


- syntax:
string strrev ( string $string )

strtolower function Output:

- converts string to lowercase


- syntax:
string strtolower ( string $str )

strtoupper function

- converts string to uppercase ucfirst () function


- syntax:
string strtoupper ( string $str ) - Make a string’s first character uppercase
- syntax:
substr function string ucfirst( string $str )

- returns part of a given string ucwords () function


- syntax:
string substr ( string $string , - converts string to uppercase
int $start [, int $length ] ) - syntax:
string ucwords ( string $str )
strlen(), strpos(), strrev(), strtolower(),
strtoupper(), substr() trim () function

Example: - stripped white spaces or other characters


from the beginning and end of a string.
<?php
$str = "The quick brown fox - syntax:
jumps over the lazy dog."; string trim ( string $str [, string
printf("Length of string: %s
$charlist ] )
<br/>", strlen($str));
ltrim () function
printf("fox string is at
position: %d <br/>", strpos($str,
- strip white spaces or other characters
'fox'));
from the beginning of a string.
printf("String reverse: %s
<br/>", strrev($str)); - syntax:
$abcStr = "AbCdeFghIjKL"; string ltrim ( string $str [, string
printf("String in lowercase: %s $charlist ] )
<br>", strtolower($abcStr));
printf("String in uppercase: %s
<br/>", strtoupper($abcStr));
rtrim () function echo $strB;
?>
- strip white spaces or other characters
from the end of a string.
– syntax:
string rtrim ( string $str [, string
$charlist ] )

strip_tags () function

- strip HTML and PHP tags from a string.


- syntax:
string strip_tags ( string $str [,
string $allowable_tags ] )

ucfirst(), ucwords(), trim(), ltrim(),


rtrim(), strip_tags()
Output:
Example:

<?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.

2. Constant name must follow the same


rules as variable names, with one
Output: exception the "$" prefix is not required for
constant names.

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

//invalid constant names Ex.iii


define('1ONE', "first value");
define(' TWO', "second value"); <?php
define('@SUM',ONE+TWO); define('X', 1000);
define('Y', 500);
?> define('Z',X - Y);
print "Subtraction of given number
Create a constant and assign your =".Z;
name. ?>

<?php Output Subtraction of given number = 500


define('NAME', "Rexx");
echo "Hello ".NAME; In the above example We define three
?> constants with name (X, Y, Z). First
subtract the value of two defined constant.
Output Hello Rexx Now result of these two value work as a
value for third define constant(Z). Pass Z
In the above example We define a inside print so it will show the subtraction
constant using define () function. first of two value.
argument for name of constant and
second for its value="phptpoint". Now Sum of two numbers and assign the
we print the value. Pass name of constant result in a variable.
inside print statement Output will become.
<?php
Sum of two numbers using constant define('ONE', 100);
define('TWO', 100);
<?php $res= ONE+TWO;
define('ONE', 100); print "Sum of two constant=".$res;
define('TWO', 100); ?>
define('SUM',ONE+TWO);
print "Sum of two constant=".SUM; Output Sum of two constant = 200
?>
In the above example We define two
Output Sum of two constant = 200 constant with name(one,two) and
value(100,100) respectively. $res
In the above example We declare three variable is also define. Now we perform
constants of name= (ONE, TWO, SUM). addition of two defined constant value and
First Add the value of two constant. Now result store in a variable ($res =
sum of these two value work as a value for one+two;). To print the result pass $res
third define constant (SUM). Now pass inside print statement.
$sum inside print it will show the sum of
two number. Building a Dollars-to-Euros Converter

<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:

- Defines whether a constant is case


insensitive. By default, this value is False,
i.e., case sensitive.

Example:
<?php

define("WELCOME",
"GeeksforGeeks!!!");

echo WELCOME, "\n";

<?php echo constant("WELCOME");


// same as previous
// This creates a case-sensitive
constant ?>
define("WELCOME",
"GeeksforGeeks"); Output:
echo WELCOME, "\n";
GeeksforGeeks!!!
// This creates a case-insensitive GeeksforGeeks!!!
constant
define("HELLO", "GeeksforGeeks", Constants are Global:
true);
echo hello; - By default, constants are automatically
global, and can be used throughout the
?> script, accessible inside and outside of
any function.
Output:
Example:
GeeksforGeeks
GeeksforGeeks <?php

constant() function define("WELCOME",


Instead of using the echo statement ,there "GeeksforGeeks");
is an another way to print constants using
the constant() function. function testGlobal() {
echo WELCOME;
Syntax }
testGlobal();
constant(name)
?>

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

- Reverse a String - Replace Text Within a String

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

- Search For a Text Within a String The PHP Date () Function


The PHP date () function formats a
The PHP strpos() function searches for a timestamp to a more readable date and
specific text within a string. If a match is time.
found, the function returns the character
position of the first match. If no match is Syntax
found, it will return FALSE.
date(format,timestamp)
Example
Parameter Description
Search for the text "world" in the string format Required.
"Hello world!": Specifies the
format of the
timestamp
<?php
timestamp Optional. Specifies
echo strpos("Hello world!", "world"); // a timestamp.
outputs 6 Default is the
?> current date and
time
Output:
A timestamp is a sequence of characters,
denoting the date and/or time at which a
certain event occurred.
Get a Date
The required format parameter of the date PHP Tip – Automatic Copyright Year
() function specifies how to format the Use the date () function to automatically
date (or time). update the copyright year on your website:

Here are some characters that are Example


commonly used for dates:
&copy; 2010-<?php echo date("Y");?>
d
Output:
- Represents the day of the month (01 to
31)

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.

So, if you need the time to be correct


according to a specific location, you can
set the timezone you want to use. Create a Date From a String with
strtotime()
The example below sets the timezone to The PHP strtotime() function is used to
"America/New_York", then outputs the convert a human readable date string into
current time in the specified format: a Unix timestamp (the number of
seconds since January 1 1970 00:00:00
Example GMT).

<?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).

The PHP mktime() function returns the


Unix timestamp for a date. The Unix
timestamp contains the number of
seconds between the Unix Epoch
PHP is quite clever about converting a
(January 1, 1970, 00:00:00 GMT) and the
string to a date, so you can put in various
time specified.
values:
Syntax
Example
mktime (hour, minute, second, month, day,
<?php
year)
$d=strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d) . "<br>";
Example
$d=strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d) . "<br>"; <?php
$d1=strtotime("July 04");
$d=strtotime("+3 Months"); $d2=ceil(($d1-time())/60/60/24);
echo date("Y-m-d h:i:sa", $d) . "<br>"; echo "There are " . $d2 ." days until 4th
?> of July.";
?>
Output:
Output:

PHP ARRAY FUNCTIONS


However, strtotime() is not perfect, so
remember to check the strings you put in
there. We have covered basics of array, indexed
arrays, associative arrays, and
multidimensional arrays. Now let's dive
More Date Examples deep into arrays and learn about the in-
The example below outputs the dates built functions for array processing in PHP.
for the next six Saturdays:
In general practice, using the right array
Example function will save you a lot of time as they
are pre-defined in PHP libraries and all
<?php
you have to do is call them to use them.
$startdate = strtotime("Saturday");
$enddate = strtotime("+6 weeks",
$startdate); Commonly used PHP5 Array Functions
Below we have a list of some
while ($startdate < $enddate) { commonly used array functions in
echo date("M d", $startdate) . "<br>"; PHP:
$startdate = strtotime("+1 week",
$startdate); sizeof($arr)
}
?> - This function returns the size of the
array, or the number of data elements
Output: stored in the array.

- It is just like count($arr) method, that we


used in previous tutorials while traversing
the array.

<?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: // new concept car by lamborghini


$concept = "estoque";
Size of the array is: 3
echo in_array($concept,
is_array($arr) $lamborghinis) ? 'Added to the Lineup'
: 'Not yet!'
- To check whether the provided data is in ?>
form of an array, we can use the
is_array() function. It returns True if the Output:
variable is an array and returns False
otherwise. Not yet!

<?php - As we can see unlike the other functions


$lamborghinis = array("Urus", above, this one takes two arguments,
"Huracan", "Aventador"); one is the value to be searched in the
array, and the second one is the array
// using ternary operator itself.
echo is_array($lamborghinis) ? 'Array' :
'not an Array'; print_r($arr)

$mycar = "Urus"; - Although this is not an array function, but


it deserves a special mention here, as we
// using ternary operator can use this function to print the array in
echo is_array($mycar) ? 'Array' : 'not the most descriptive way possible. This
an Array'; function prints the complete representation
of the array, along with all the keys and
?> values.

Output: <?php
$lamborghinis = array("Urus",
Array "Huracan", "Aventador");

not an Array print_r($lamborghinis);


?>
in_array($var, $arr)
Output:
- When using an array, we may often want
to check whether a certain value is Array (
present in the array or not. For example, if [0] => "Urus"
get a list of certain cars, like we do in [1] => "Huracan"
almost all our examples, to check if a [2] => "Aventador"
certain car is added into the array, we can )
use the in_array function.
array_merge($arr1, $arr2)
- Let's take an example and see,
- If you want to combine two different
<?php arrays into a single array, you can do so
using this function. It doesn't matter
whether the arrays to be combined are of a separate array, then we can use
same type (indexed, associative etc) or array_values() function.
different types, using this function we can
combine them into one single array. - Let's take the array $merged formed in
the example above,
- Let's take an example where we will
merge an indexed array and an <?php
associative array. $hatchbacks = array(
"Suzuki" => "Baleno",
<?php "Skoda" => "Fabia",
$hatchbacks = array( "Hyundai" => "i20",
"Suzuki" => "Baleno", "Tata" => "Tigor"
"Skoda" => "Fabia", );
"Hyundai" => "i20",
"Tata" => "Tigor" // friends who own the above cars
); $friends = array("Vinod", "Javed",
"Navjot", "Samuel");
// friends who own the above cars
$friends = array("Vinod", "Javed", // let's merge the two arrays into one
"Navjot", "Samuel"); $merged = array_merge($hatchbacks,
$friends);
// let's merge the two arrays into one
$merged = array_merge($hatchbacks, //getting only the values
$friends); $merged = array_values($merged);

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 - This function sorts the array elements in


$lamborghinis = array("Urus", ascending order. In case of a string value
"Huracan", "Aventador"); array, values are sorted in ascending
alphabetical order.
// adding a new element at the end
- Some other sorting functions are: $numbers = array_map('addOne',
asort(), arsort(), ksort(), krsort() and $numbers);
rsort().
print_r($numbers)
<?php ?>
$lamborghinis = array("Urus",
"Huracan", "Aventador", "Estoque"); Output:

// sort the array Array (


sort($lamborghinis); [0] => 11
[1] => 21
print_r($lamborghinis); [2] => 31
?> [3] => 41
[4] => 51
Output: )

Array ( The function array_walk($arr,


[0] => Aventador 'function_name') works just like the
[1] => Estoque array_map() function.
[2] => Huracan
[3] => Urus array_flip()
)
- This function interchanges the keys and
array_map(‘function_name’, $arr) the values of a PHP associative array.

- If you want to perform certain operation <?php


on all the values stored in an array, you $hatchbacks = array(
can do it by iterating over the array using a "Suzuki" => "Baleno",
for loop or foreach and performing the "Skoda" => "Fabia",
required operation on all the values of the "Hyundai" => "i20",
array. "Tata" => "Tigor"
);
- Or you can use the function array_map
(). All we have to do is define a separate // we can directly print the result of
function to which we will provide the array flipping
values stored in the array one by one print_r(array_flip($hatchbacks));
(one at a time) and it will perform the ?>
operation on the values. Let's have an
example, Output:

<?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:

- If you want to pick random data element Array (


from an array, you can use the [0] => blue
array_rand() function. This function [1] => green
randomly selects one element from the [2] => white
given array and returns it. )

- In case of indexed array, it will return the PHP Strings


index of the element, in case of In this tutorial you will learn how to store
associative array, it will return the key of and manipulate strings in PHP.
the selected random element.
String in PHP
<?php
A string is a sequence of letters, numbers,
$colors = array("red", "black", "blue",
special characters and arithmetic values
"green", "white", "yellow");
or combination of all. The simplest way to
create a string is to enclose the string
echo "Color of the day: ".
literal (i.e., string characters) in single
$colors[array_rand($colors)];
quotation marks ('), like this:
?>
$my_string = 'Hello World';
Output:
You can also use double quotation
Color of the day: green
marks ("). However, single, and double
quotation marks work in different ways.
Every time you run the above script, it will
Strings enclosed in single-quotes are
return a random color value from the
treated almost literally, whereas the strings
array.
delimited by the double quotes replaces
variables with the string representations of
their values as well as specially
interpreting certain escape sequences.
Output:
The escape-sequence replacements
are:

\n

- is replaced by the newline character

\r

- is replaced by the carriage-return


character Manipulating PHP Strings
PHP provides many built-in functions for
\t manipulating strings like calculating the
length of a string, find substrings or
- is replaced by the tab character characters, replacing part of a string with
different characters, take a string apart,
\$ and many others. Here are the examples
of some of these functions.
- is replaced by the dollar sign itself ($)
Calculating the Length of a String
\” The strlen() function is used to calculate
the number of characters inside a string. It
- is replaced by a single double-quote (") also includes the blank spaces inside the
string.
\\
Example
- is replaced by a single backslash (\)
<?php
Here's an example to clarify the $my_str = 'Welcome to Tutorial
differences between single and double Republic';
quoted strings:
// Outputs: 28
Example echo strlen($my_str);
?>
<?php
$my_str = 'World'; Output:
echo "Hello, $my_str!<br>"; // Displays:
Hello World!
echo 'Hello, $my_str!<br>'; // Displays:
Hello, $my_str!

echo '<pre>Hello\tWorld!</pre>'; // Counting Number of Words in a String


Displays: Hello\tWorld! The str_word_count() function counts
echo "<pre>Hello\tWorld!</pre>"; // the number of words in a string.
Displays: Hello World!
echo 'I\'ll be back'; // Displays: I'll be Example
back
?> <?php
$my_str = 'The quick brown fox jumps
over the lazy dog.';
echo "The text was replaced $count
// Outputs: 9 times.";
echo str_word_count($my_str); ?>
?>
The output of the above code will be:
Output:
Output:

The text was replaced 2 times.

Replacing Text within Strings Reversing a String


The str_replace() replaces all The strrev() function reverses a string.
occurrences of the search text within the
target string. Example

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.

<?php The default time zone is set in the php.ini


date(format,[timestamp]); file.
?>
It can also be set programmatically using
HERE, date_default_timezone_set function.

“date(…)” The code below displays the current time


stamp.
- is the function that returns the current
time on the server. <?php
echo time();
“format” ?>

- 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

- for PHP date format YYYY-MM-DD Output:

o “Y”

- to display the current year

o “[timestamp]”

- is optional. If no timestamp has been


provided, PHP will get the use the php Note: the value of the timestamp is not a
current date time on the server. constant. It changes every second.

Let’s look at a basic example that displays


Getting a list of available time zone
the current year.
identifiers
Before we look at how to set the default
<?php
time zone programmatically, let’s look at
echo date("Y");
how to get a list of supported time zones.
?>
<?php
Output:
$timezone_identifiers =
DateTimeZone::listIdentifiers();
2018
foreach($timezone_identifiers as $key
TimeStamp => $list){
A timestamp is a numeric value in seconds
between the current time and value as at echo $list . "<br/>";
1st January, 1970 00:00:00 Greenwich }
Mean Time (GMT). ?>
HERE, <?php
date_default_timezone_set ( string
“$timezone_identifiers=DateTimeZone:: $timezone_identifier );
listIdentifiers();” ?>

- calls the listIdentifiers static method of HERE,


the DateandTime Zone built in class.
“date_default_timezone_set()”
- The listIdentifiers method returns a list of
constants that are assigned to the variable - is the function that sets the default time
$timezone_identifiers. zone

“foreach{…}” “string $timezone_identifier”

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

Assuming you have saved the file


set_time_zone.php in the phptuts folder,
browse to the URL
http://localhost/phptuts/set_time_zone.
php

Output:
PHP set Timezone Programmatically
The date_default_timezone_set function
allows you to set the default time zone
from a PHP script.

The set time zone will then be used by all


date php function scripts. It has the
following syntax.
PHP Mktime Function
The mktime function returns the <?php
timestamp in a Unix format. echo mktime(0,0,0,10,13,2025);
?>
It has the following syntax.
HERE,
<?php
mktime(hour, minute, second, month, “0,0,0”
day, year, is_dst);
?> - is the hour, minute, and seconds
respectively.
HERE,
“13”
“mktime(…)”
- is the day of the month
- is the make php timestamp function
“10”
“hour”
- is the month of the year
- is optional, it is the number of hours
“2025”
“minute”
- is the year
- is optional, it is the number of minutes
Output:
“second”
1760328000
- is optional, it is the number of seconds
PHP Date function reference
“month” The table below shows the common
parameters used when working with the
- is optional, it is the number of the month date php function.

“day” PHP Time parameters

- is optional, it is the number of the day Param Description Example


eter
“year” “r” Returns the full <?php
date and time echo
- is optional, it is the number of the year date("r"
);
“is_dst” ?>
“a”, “A” Returns whether <?php
- is optional, it is used to determine the the current time is echo
day saving time (DST). 1 is for DST, 0 if it am or pm, AM or date("a"
is not and -1 if it is unknown. PM respectively );
echo
date("A"
Let’s now look at an example that creates
);
a timestamp for the date 13/10/2025 using ?>
the mktime function.
“g”, “G” Returns the hour <?php “l” Returns day name of the <?php
without leading echo week [Sunday to echo
Saturday] date("l");
zeroes [1 to 12], [0 date("g" ?>
to 23] respectively ); “w” Returns day of the week <?php
echo without leading zeroes [0 echo
date("G" to 6] Sunday is date("w");
represented by zero (0) ?>
); through to Saturday
?> represented by six (6)
“h”, “H” Returns the hour <?php “z” Returns the day of the <?php
with leading zeros echo year without leading echo
[01 to 12], [00, to date("h" spaces [0 through to 365] date("z");
?>
23] respectively );
echo
date("H" Output:
);
?>
“i", “s” Returns the <?php
minutes/seconds echo
with leading zeroes date("i"
[00 to 59] );
echo
date("s"
);
?> Month Parameters

Output: Parameter Description Example


“m” Returns the <?php
month number echo
with leading date("m")
zeroes [01 to ;
12] ?>
“n” Returns the <?php
month number echo
without leading date("n")
zeroes [01 to ;
12] ?>
“M” Returns the first <?php
3 letters of the echo
month name date("M")
Day parameters [Jan to Dec] ;
?>
Parameter Description Example “F” Returns the <?php
“d” Returns the day of the <?php month name echo
month with leading echo [January to date("F")
zeroes [01 to 31] date("d");
?>
December] ;
“j” Returns the day of the <?php ?>
month without leading echo “t” Returns the <?php
zeroes [1 to 31] date("j"); number of days echo
?> in a month [28 date("t")
“D” Returns the first 3 letters <?php
of the day name [Sub to echo to 31] ;
Sat] date("D"); ?>
?>
Output: STUDY GUIDE

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.

Year Parameters Syntax:

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

strtolower function - strip white spaces or other characters


from the end of a string.
- converts string to lowercase – syntax:
- syntax: string rtrim ( string $str [, string
string strtolower ( string $str ) $charlist ] )

strtoupper function strip_tags () 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)

- get the unix timestamp (January 1,


1970) for a given date. (With strict
notice)
- same as time () function (without strict
notice)
- syntax:
int mktime ([ int $hour = date("H")
[, int $minute = date("i")
[, int $second = date("s")
[, int $month = date("n")
[, int $day = date("j")
[, int $year = date("Y")
[, int $is_dst = -1 ]]]]]]] )
APPLICATIONS DEVELOPMENT AND EMERGING TECHNOLOGIES
QUESTIONNAIRE
FORMATIVE 3 D. apple

1.) $t = 100; 5.) You use can functions in different


function one(){ ways.
echo “value”;
} A. False
one(); B. True

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

A. Error 9.) Id the keyword used to declare a


B. 105 function.
C. 15
D. 5 A. ft
B. function
4.) $fruit = array(“orange”, “apple”, C. func
“grape”, “banana”); D. fntn

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. True what is the value of the $t after execute


B. False the code?

12.) is used to retain the values calls to A. 1000


the same function. B. Error
C. 100
A. Local variables D. 1
B. Global variables
C. Dynamic variables 17.) functions that are provided by the
D. Static variables user of the program.

13.) $f = array{ A. User function


‘102’ => “red”, B. User defined function
‘101’ => “blue”, C. Predefined function
‘100’ => “yellow”); D. Program function
ksort($f);
print_r($f); 18.) references a corresponding value

What is the key of the yellow? A. Array number


B. Array index
A. Error C. Array setting
B. 102 D. Array collection
C. 100
D. 101 19.) Functions are limited to 1 per code
only.
14.) Sorts by value in reverse order; keeps
the same key. A. False – not limited.
B. True
A. sort($array)
B. arsort($array) 20.) A function that is declared inside a
C. rsort($array) function is said to be hidden.
D. asort($array)
A. False
15.) $num=array(1,2,3,4,5); B. True
foreach($num as $val){
echo $val 21.) Sorts by value; assign new numbers
} as the keys.

What is the output of the code? A. asort($array)


B. arsort($array)
A. 1 C. sort($array)
B. Error D. rsort($array)
C. 12345
D. 5
22.) ksort() and krsort() used to sort C. banana
elements by values. D. apple

A. True 29.) foreach (_____ as $value)


B. False – by keys
A. arr$
23.) PHP array does not need to declare B. array
how many elements that the array variable C. arr
have. D. $arr

A. False 30.) Function can be put anywhere of the


B. True code.

24.) We use static keyword to declare a A. False


variable inside a function that will act as B. True
accumulator variable this will let the
program remember the last value of the 31.) PHP array does need to declare how
variable that was used. many elements that the array variable
have.
A. True
B. False A. False
B. True
25.) Functions are designed to allow you
to reuse the same code in different 32.) function a($a, $){
locations. $return $a+$b;
}
A. False echo a(6, 5);
B. True
what is the value of $a?
26.) is used to aggregate a series of
similar items together, arranging and A. 6
dereferencing them in some specific way. B. 11
C. 5
A. Function D. Error
B. Array
C. Variable 33.) $g = 200;
D. Index function a(){echo “5”;}
function b(){echo “4”;}
27.) Array index is also known as Array a();
Keys.
what is the output of the code?
A. True
B. False A. 5
B. 200
28.) $fruit = array(“orange”, “apple”, C. A
“grape”, “banana”); D. 4

What is the value of index 3?

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?

35.) You can pass values to a function and A. Valid


you can ask functions to return a value. B. Invalid - $num

A. True 41.) function keyword is used in PHP to


B. False declare a function.

36.) To gain access to a variable that is A. True


outside from the function we use the B. False
global keyword.
42.) function a ($a, $b){
A. False return $a+$b;
B. True }
echo a(5, 4):
37.) asort(), ksort(), arsort(), and ksort()
maintains its reference for each values. what is the name of the parameter?

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

45.) function disp(){


function disp2(){
echo “hello”;
}
} 51.) Syntax of a function
disp2();
A. Param(function name){}
A. disp B. Function name(param){}
B. error C. Param_function
C. hello D. Function name {param}
D. blank
52.) Sorts by key in reverse order
46.) Function can only do something
without passing values. A. ksort($array)
B. krsort($array)
A. True C. kusort($array)
B. False D. usort($array)

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

A. print_r() 56.) $s = “variable”;


B. print_a() function f(){
C. print_c() echo “function called”;
D. print_p() echo “$s”;
}
f(); D. print_a

what is the output of the code? 2.) $num=array(1,2,3,4,5);


foreach(num as $val){
A. function called. echo $val;
B. function called variable. }
C. function variable
D. function called undefined variables: Check the code if valid or invalid?
s.
A. Valid
57.) Array index in PHP can be also B. Invalid
called.
3.) You can pass values to a function and
A. Array keys you can ask functions to return a value.
B. Array set
C. Array storage A. False
D. Array number B. True

58.) $g = 200; 4.) $f = array(


function a(){echo “5”;} ‘102’ => “red”,
function b(){echo “4”;} ‘101’ => “blue”,
a();b(); ‘100’ => “yellow”);
ksort($f);
what is the output of the code? print_r($f);

A. 200 What is the key of the yellow?


B. Error
C. 45 A. 101
D. 54 B. 100
C. 102
59.) foreach($arr as _____) D. Error

A. val$ 5.) is a statement used to iterate or loop


B. value$ through the element in an array.
C. $value
D. val A. everyone()
B. foreach()
60.) You can use only 10 for Array C. everyeach()
elements. D. seteach()

A. True 6.) You can create your own function


B. False – any number inside of a php code.

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)

10.) Function is a group of PHP A. R


statements that performs a specific task. B. N
C. W
A. False D. C
B. True
18.) strip HTML and PHP tags from a
11.) Sorts by value in reverse order; string.
assign new number as the keys.
A. tags_get()
A. asort($array) B. strip_tags()
B. sort($array) C. tags_search()
C. arsort($array) D. find_tags()
D. rsort($array)

12.) foreach($arr as _____)

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

what is the value of the $g?

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

45.) used to format a local time and date A. M


B. R
A. time() C. Y
B. time_date() D. N
C. date_time()
D. date() 52.) Syntax for floor

46.) Syntax for random number with A. floor()


minimum and maximum value B. fl()
C. flr()
A. int ran(int $min, int $max) D. flor()
B. int rand(int $min, int $max)
C. int random(int $min, int $max) 53.) Syntax to get a part of a given string
D. int rndm(int $min, int $max)
A. string partstr (string $string, int $start [,
47.) return the value length of a string int $length ] )
B. string strpart (string $string, int $start [,
A. stringlen int $length ] )
B. lenstr C. string substr (string $string, int
C. lengthstring $start [, int $length ] )
D. strlen D. string strsub (string $string, int $start [,
int $length ] )
48.) define(‘Max_n’, 10);
54.) syntax for reverse a string
What is the name of the define function?
A. string strrev (string $string)
A. Define B. string revstr (string $string)
B. Max C. string stringrev (string $string)
C. Max_n D. string revstring (string $string)
D. 10

49.) Most of the developers used include


functions for their

A. Titles
B. Footer
C. Body
D. Content

You might also like