DWPD Unit-3
DWPD Unit-3
Arrays
• An array is a single variable that can hold more than one value at once.
• You can think of an array as a list of values.
• Each value within an array is called an element, and each element is referenced by its own
index, which is unique to that array.
• To access an elements value — whether you are creating, reading, writing, or deleting the
element you use that elements index.
Types of Array
• In PHP, there are three types of arrays:
✓ Indexed arrays (Numeric arrays) - Arrays with a numeric index
✓ Associative arrays - Arrays with named keys
✓ Multidimensional arrays (Nested arrays) - Arrays containing one or more arrays
Creating arrays
• You can use array() function to create array.
• Syntax: $array_name=array ( value1, value2 …valueN);
• There are two ways to create indexed arrays.
• The index can be assigned automatically (index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");
• The index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Length of an Array
• The count() function is used to return the length (the number of elements) of an array.
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Changing Elements
• You can also change value of element using index.
<?php Output:
$myarray=array("Apache", "MySQL", "PHP"); Apache
$myarray[1]="Oracle"; Oracle
for($i=0;$i<3;$i++) PHP
{ echo $myarray[$i]."<br>"; }
?>
<?php Output:
$myarray=array("Apache", "MySQL", "PHP"); Array ( [0] => Apache [1] => MySQL [2] => PHP )
print_r($myarray); Array ( [0] => Apache [1] => MySQL [2] => PHP [3]
echo "<br>"; => Oracle )
$myarray[]="Oracle"; Array ( [0] => Apache [1] => MySQL [2] => PHP [3]
print_r($myarray); => Oracle [4] => Java [5] => .Net )
echo "<br>";
array_push($myarray,"Java",".Net");
print_r($myarray);
?>
Remove Element
• Unset () is used to destroy a variable in PHP. It can be used to remove a single variable, multiple
variables, or an element from an array.
Searching element
• The array_search() function search an array for a value and returns the key.
• Syntax: array_search(value,array,strict)
✓ value: Required. Specifies the value to search for
✓ array: Required. Specifies the array to search in
✓ strict: Optional. If this parameter is set to TRUE, then this function will search for identical
elements in the array.
<?php Output:
$a=array("A"=>"5","B"=>5); A
echo array_search(5,$a); B
echo array_search(5,$a,true);
?>
• The in_array() function searches an array for a specific value.
• Syntax: in_array(search,array,type)
✓ search: Required. Specifies the what to search for
✓ array: Required. Specifies the array to search
✓ type: Optional. If this parameter is set to TRUE, the in_array() function searches for the
specific type in the array.
<?php Output:
$people=array("Peter", "Joe", "Glenn", 23); Match found
if (in_array("23",$people)) Match not found
{ echo "Match found<br>"; }
else { echo "Match not found<br>"; }
if (in_array("23", $people, TRUE))
{ echo "Match found<br>"; }
else { echo "Match not found<br>"; }
?>
Sorting array
• sort() - sort arrays in ascending order
• rsort() - sort arrays in descending order
<?php Output:
$srtArray=array(2,8,9,5,6,3); 235689
for ($i=0; $i<count($srtArray); $i++)
{ for ($j=0; $j<count($srtArray); $j++)
{ if ($srtArray[$j] > $srtArray[$i])
{ $tmp = $srtArray[$i];
$srtArray[$i] = $srtArray[$j];
$srtArray[$j] = $tmp;
}
}
}
foreach($srtArray as $item)
{ echo $item."<br>\n"; }
?>
<?php Output:
$srtArray=array(2,8,9,5,6,3); 235689
sort($srtArray);
foreach($srtArray as $item)
{ echo $item."<br>\n"; }
?>
Associative Array
• The associative part means that arrays store element values in association with key values
rather than in a strict linear index order.
• If you store an element in an array, in association with a key, all you need to retrieve it later
from that array is the key value.
• Key may be either numeric or string.
• You can use array() function to create associative array.
• Syntax: $array_name=array(key1=>value1, key1=>value1,….. keyN=>valueN);
• There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
OR
$age["Peter"] = "35";
$age["Ben"] = "37";
$age["Joe"] = "43";
Multidimensional Array
• Earlier, we have described arrays that are a single list of key/value pairs.
• However, sometimes you want to store values with more than one key.
• This can be stored in multidimensional arrays.
• A multidimensional array is an array containing one or more arrays.
• PHP understands multidimensional arrays that are two, three, four, five, or more levels deep.
• First, take a look at the following table:
Name Stock Sold
Volvo 22 18
BMW 15 13
Saab 5 2
• Example:
<?php Output:
$cars = array Volvo 22 18
( array("Volvo",22,18), BMW 15 13
array("BMW",15,13), Saab 5 2
array("Saab",5,2),
);
for ($row = 0; $row < 4; $row++)
{ echo "<br>";
for ($col = 0; $col < 3; $col++)
{ echo $cars[$row][$col]." "; }
}
?>
<?php Output:
function swap($num1, $num2) Before Swap
{ num1=10
$temp = $num1; num2=20
$num1=$num2; After Swap
$num2=$temp; num1=10
} num2=20
$num1=10;
$num2=20;
echo "Before Swap"."<br>";
echo "num1=".$num1."<br>";
echo "num2=".$num2."<br>";
swap($num1,$num2);
echo "After Swap"."<br>";
echo "num1=".$num1."<br>";
echo "num2=".$num2."<br>";
?>
Call-by-Reference
• Call by reference means passing the address of a variable where the actual value is stored. The
called function uses the value stored in the passed address; any changes to it do affect the
source variable.
<?php Output:
function swap(&$num1, &$num2) Before Swap
{ num1=10
$temp = $num1; num2=20
$num1=$num2; After Swap
$num2=$temp; num1=20
} num2=10
$num1=10;
$num2=20;
echo "Before Swap"."<br>";
echo "num1=".$num1."<br>";
echo "num2=".$num2."<br>";
swap($num1,$num2);
echo "After Swap"."<br>";
echo "num1=".$num1."<br>";
echo "num2=".$num2."<br>";
?>
Variables Scope
• In PHP, variables can be declared anywhere in the script.
• The scope of a variable is the part of the script where the variable can be referenced/used.
• PHP has three different variable scopes:
✓ local
✓ global
✓ static
Global
• A variable declared outside a function has a global scope and can only be accessed outside a
function:
<?php
$x = 5; // global scope
function myTest()
{
echo "Variable x inside function is: $x"; // using x inside this function will generate an error
}
//myTest();
echo "Variable x outside function is: $x";
?>
• The global keyword is used to access a global variable from within a function.
• To do this, use the global keyword before the variables (inside the function):
global $x;
Local
• A variable declared within a function has a local scope and can only be accessed within that
function.
<?php
function myTest()
{
$x = 5; // local scope
echo "Variable x inside function is: $x";
}
myTest();
//echo "Variable x outside function is: $x"; // using x outside the function will generate an error
?>
Static
• Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable not to be deleted. We need it for a further job.
String Function
chr
• Returns a character from a specified ASCII value.
• Syntax: chr(ascii)
<?php output:
echo chr(65); A
?>
ord
• Returns the ASCII value of the first character of a string.
• Syntax: ord(string)
<?php Output:
echo ord("A")."<br />"; 65
echo ord("And"); 65
?>
strtolower
• Converts a string to lowercase letters.
• Syntax: strtolower(string)
<?php Output:
echo strtolower("HELLO"); hello
?>
strtoupper
• Converts a string to uppercase letters.
• Syntax: strtoupper(string)
9 Dept: CE DWPD (3350702) Twincle
Kalyan Polytechnic Unit 3
<?php Output:
echo strtolower("hello"); HELLO
?>
strlen
• Returns the length of a string.
• Syntax: strlen(string)
<?php Output:
echo strlen("hello hi"); 8
?>
ltrim:
• Remove whitespace from the left side of a string.
• Syntax: ltrim(string,charlist)
✓ charlist:- Optional. Specifies which characters to remove from the string. If omitted, all of
the following characters are removed:"\0" – NULL, "\t" – tab, "\n" – new line, "\r" – carriage
return, “ ” – white space.
<?php Output:
$str="Hello"; ello
echo ltrim($str,"H")."<br>"; Hello
$str=" Hello";
echo ltrim($str);
?>
rtrim
• Remove whitespace from the right side of a string.
• Syntax: rtrim(string,charlist)
✓ charlist:- Optional. Specifies which characters to remove from the string. If omitted, all of
the following characters are removed:"\0" – NULL, "\t" – tab, "\n" – new line, "\r" – carriage
return, “ ” – white space.
<?php Output:
$str="Hello"; Hell
echo rtrim($str,"o")."<br>"; Hello
$str="Hello ";
echo rtrim($str);
?>
trim
• Remove whitespace from both sides of a string.
• Syntax: trim(string,charlist)
✓ charlist:- Optional. Specifies which characters to remove from the string. If omitted, all of
the following characters are removed:"\0" – NULL, "\t" – tab, "\n" – new line, "\r" – carriage
return, “ ” – white space.
substr
• Returns a part of a string.
• Syntax: substr(string,start,length)
✓ start: Required. Specifies where to start in the string. A positive number - Start at a
specified position in the string. A negative number - Start at a specified position from the
end of the string. 0 - Start at the first character in string.
✓ length: Optional. Specifies the length of the returned string. Default is to the end of the
string. A positive number - The length to be returned from the start parameter. Negative
number - The length to be returned from the end of the string.
<?php Output:
echo substr("Hello world",3,2); lo
echo substr("Hello world",-3,2); rl
echo substr("Hello world",3,-2); lo wor
echo substr("Hello world",-3,-2); r
?>
strcmp
• Compares two strings (case-sensitive).
• strcmp function returns: 0 - if the two strings are equal, negative - if string1 is less than string2
and positive - if string1 is greater than string2.
• Syntax: strcmp(string1,string2)
<?php Output:
echo strcmp("hello","hello"); 0
echo strcmp("hello","hi"); -1
echo strcmp("hi","hello"); 1
?>
strcasecmp
• Compares two strings (case-insensitive)
• strcmp function returns: 0 - if the two strings are equal, negative - if string1 is less than string2
and positive - if string1 is greater than string2.
• Syntax: strcasecmp(string1,string2)
<?php Output:
echo strcmp("hello","hello"); 1
echo strcasecmp("hello","Hello"); 0
?>
strrpos
• Returns the position of the last occurrence of a string inside another string (case-sensitive).
• If the string is not found, this function returns FALSE.
• Syntax:- strpos(string,find,start)
✓ find:- Required. Specifies the string to find
✓ start:- Optional. Specifies where to begin the search
<?php Output:
echo strrpos("hello","l"); 3
?>
strstr
• Finds the first occurrence of a string inside another string (case-sensitive).
• This function returns the rest of the string (from the matching point), or FALSE, if the string to
search for is not found.
• Syntax: strstr(string,search)
✓ search: Required. Specifies the string to search for. If this parameter is a number, it will
search for the character matching the ASCII value of the number.
<?php Output:
echo strstr("Hello world!","wor"); world!
echo strstr("Hello world!","Wor");
?>
stristr
• Finds the first occurrence of a string inside another string (case-insensitive).
• This function returns the rest of the string (from the matching point), or FALSE, if the string to
search for is not found.
• Syntax: stristr(string,search)
<?php Output:
echo stristr("Hello world!","Wor"); world!
?>
strrev:
• Reverses a string.
• Syntax: strrev(string)
<?php Output:
echo strrev("hello"); olleh
?>
Math Function
abs
• Returns the absolute value of a number.
• Syntax: abs(x)
<?php Output:
echo abs(-6.7)."<br>"; 6.7
echo abs(-3)."<br>"; 3
?>
ceil
• Returns the smallest integer value that is greater than or equal to a x.
• Syntax: ceil(x)
<?php Output:
echo ceil(0.60)."<br>"; 1
echo ceil(5)."<br>"; 5
echo ceil(-4.9); ?> -4
floor
• Returns the largest integer value that is less than or equal to a x.
• Syntax: floor(x)
<?php Output:
echo ceil(0.60)."<br>"; 0
echo ceil(5)."<br>"; 5
echo(ceil(-4.9)."<br>"); -5
?>
13 Dept: CE DWPD (3350702) Twincle
Kalyan Polytechnic Unit 3
round
• Rounds a number to the nearest integer.
• Syntax: round(x,precision)
✓ precision: Optional. The number of digits after the decimal point
<?php Output:
echo round(5.335,2)."<br>"; 5.34
echo round(0.49); 0
?>
fmod
• Returns the remainder (modulo) of the division of the arguments.
• Syntax: fmod(x,y)
<?php Output:
echo fmod(5,2); 1
?>
min
• Returns the number with the lowest value from specified numbers.
• Syntax: min(x1,x2,x3…)
<?php Output:
echo min(5,2,1,-4); -4
?>
max
• Returns the number with the highest value from specified numbers.
• Syntax: max(x1,x2,x3…)
<?php Output:
echo max(5,2,1,-4); 5
?>
pow
• Returns the value of x to the power of y.
• Syntax: pow(x,y)
<?php Output:
echo pow(5,2); 25
?>
sqrt
• Returns the square root of a number x.
• Syntax: sqrt(x)
<?php Output:
echo sqrt(25); ?> 5
Date Function
date
• Formats a local time/date.
• Syntax: date(format,timestamp)
✓ format: Required. Specifie the format of date and time to be returned.
• d - The day of the month (from 01 to 31)
• m - A numeric representation of a month (from 01 to 12)
• M - A short textual representation of a month (three letters)
• Y - A four digit representation of a year
• y - A two digit representation of a year
<?php Output:
echo date("d/m/y")."<br>"; 11/08/15
echo date("d M, Y"); 11 Aug, 2015
?>
getdate
• Returns an array that contains date and time information for a UNIX timestamp.
• The returning array contains ten elements with relevant information needed when formatting a
date string: [seconds] – seconds, [minutes] – minutes, [hours] – hours, [mday] - day of the
month, [wday] - day of the week, [year] – year, [yday] - day of the year, [weekday] - name of
the weekday, [month] - name of the month.
• Syntax: getdate(timestamp)
✓ Timestamp:- Optional. Specifies the time in Unix time format
<?php Output:
print_r (getdate()); Array ( [seconds] => 3 [minutes] => 49 [hours] =>
?> 17 [mday] => 11 [wday] => 2 [mon] => 8 [year] =>
2015 [yday] => 222 [weekday] => Tuesday
[month] => August [0] => 1439308143 )
time
• The time() function returns the current time as a Unix timestamp (the number of seconds since
January 1 1970 00:00:00 GMT).
• Syntax: time(void)
<?php Output:
echo time(); 1439309922
?>
mktime
• The mktime() function returns the Unix timestamp for a date. This timestamp contains the
number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time
specified.
• Syntax: mktime(hour,minute,second,month,day,year,is_dst)
✓ hour, minute, second, month, day, year: Optional. Specifies the hour, minute, second,
month, day, year.
✓ is_dst: Optional. Set this parameter to 1 if the time is during daylight savings time (DST), 0 if
it is not, or -1 (the default) if it is unknown.
<?php Output:
echo(date("M-d-Y",mktime(0,0,0,12,36,2001))."<br />"); Jan-05-2002
echo(date("M-d-Y",mktime(0,0,0,1,1,99))."<br />"); Jan-01-1999
?>