0% found this document useful (0 votes)
3 views16 pages

DWPD Unit-3

The document provides an overview of arrays in PHP, detailing their types, creation, accessing elements, and manipulation methods. It covers indexed, associative, and multidimensional arrays, along with functions for adding, removing, and sorting elements. Additionally, it explains user-defined functions, variable scope, and the difference between call-by-value and call-by-reference.

Uploaded by

Twinkle Vyas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views16 pages

DWPD Unit-3

The document provides an overview of arrays in PHP, detailing their types, creation, accessing elements, and manipulation methods. It covers indexed, associative, and multidimensional arrays, along with functions for adding, removing, and sorting elements. Additionally, it explains user-defined functions, variable scope, and the difference between call-by-value and call-by-reference.

Uploaded by

Twinkle Vyas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Kalyan Polytechnic 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

Indexed arrays (Numeric arrays)


• In numeric array each element having numeric key associated with it that is starting from 0.

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

Accessing Array Elements


• The print_r() function is used to print information about a variable.
<?php Output:
$myarray=array("A","B","C"); Array ( [0] => A [1] => B [2] => C )
print_r($myarray);
?>

1 Dept: CE DWPD (3350702) Twincle


Kalyan Polytechnic Unit 3
• You can refer to individual element of an array in PHP script using its key value as shown below:
<?php Output:
$myarray=array("A","B","C"); B
echo $myarray[1];
?>
• In Numeric Array you can use for, while or do while loop to iterate through each element in
array because in numeric array key values are consecutive.
<?php Output:
$myarray=array("Apache", "MySQL", "PHP"); Apache
for($i=0;$i<3;$i++) MySQL
{ echo $myarray[$i]."<br>"; } PHP
?>

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

Add elements to array


• The array_push() function inserts one or more elements to the end of an array.
• Syntax: array_push(array,value1,value2...)
✓ array: Required. Specifies an array
✓ value1: Required. Specifies the value to add
✓ value2: Optional. Specifies the value to add

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

2 Dept: CE DWPD (3350702) Twincle


Kalyan Polytechnic Unit 3
• Syntax: unset (var1, var2....)
✓ var1, var2: The variable to be unset.
<?php Output:
$cars = array("Volvo", "BMW", "Toyota", Array ( [0] => Volvo [1] => BMW [2] => Toyota [35]
"35"=>"Maruti"); => Maruti )
print_r($cars); Array ( [1] => BMW [2] => Toyota )
unset($cars[0]);
unset($cars["35"]);
echo "<br>";
print_r($cars);
?>

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

3 Dept: CE DWPD (3350702) Twincle


Kalyan Polytechnic Unit 3
• asort() - sort associative arrays in ascending order, according to the value
• ksort() - sort associative arrays in ascending order, according to the key
• arsort() - sort associative arrays in descending order, according to the value
• krsort() - sort associative arrays in descending order, according to the key

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

• Sort array using function.

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

4 Dept: CE DWPD (3350702) Twincle


Kalyan Polytechnic Unit 3
• You can refer to individual element of an array in PHP using its key value.
<?php Output:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); Ben:37
echo "Ben:".$age["Ben"];
?>
• In associative array you cannot use for, while or do…while loop to iterate through each element
in array because in Associative array key value are not consecutive.
• So you have to use foreach loop.
<?php Output:
$myarray=array("Name"=>"James", "Age"=>25, "Gender"=>"Male"); James
foreach($myarray as $item) 25
{ echo $item."<br>"; } Male
?>

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]." "; }
}
?>

User Defined Functions


• Besides the built-in PHP functions, we can create our own functions.
• A function is a block of statements that can be used repeatedly in a program.

5 Dept: CE DWPD (3350702) Twincle


Kalyan Polytechnic Unit 3
• A function will not execute immediately when a page loads.
• A function will be executed by a call to the function.

Create a User Defined Function


• A user defined function declaration starts with the word "function".
• Syntax:
function functionName()
{ Code to be executed; }
• Example:
<?php Output:
function writeMsg() Hello world!
{ echo "Hello world!"; }
writeMsg(); // call the function
?>

Function Arguments and returning values from function


• Information can be passed to functions through arguments. An argument is just like a variable.
• Arguments are specified after the function name; inside the parentheses separate with comma.
<?php Output:
function addFunction($num1, $num2) Addition=30
{ $sum = $num1 + $num2;
return $sum;
}
$result=addFunction(10, 20);
echo "Addition=".$result;
?>

Default values for arguments


• You can specify default values for arguments.
• If the argument is omitted from the function call the default is used.
• The default value must be a constant expression such as a string, integer or NULL.
• You can have multiple arguments with default values. Default values assign from right to left.
<?php Output:
function addFunction($num1, $num2=5) Addition=30
{ Addition=15
$sum = $num1 + $num2;
return $sum;
}
$result=addFunction(10,20);
echo "Addition=".$result."<br>";
$result=addFunction(10);
echo "Addition=".$result;
?>

6 Dept: CE DWPD (3350702) Twincle


Kalyan Polytechnic Unit 3
Call-by-Value
• The default behavior for user-defined functions in PHP is call-by-value.
• Call by value means passing the value directly to a function. The called function uses the value
in a local variable; any changes to it do not 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=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>";
?>

7 Dept: CE DWPD (3350702) Twincle


Kalyan Polytechnic Unit 3

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.

8 Dept: CE DWPD (3350702) Twincle


Kalyan Polytechnic Unit 3
• To do this, use the static keyword when you first declare the variable:
<?php Output:
function myTest() 0
{ static $x = 0; 1
echo $x; 2
$x++;
}
myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>
• Then, each time the function is called, that variable will still have the information it contained
from the last time the function was called.

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.

10 Dept: CE DWPD (3350702) Twincle


Kalyan Polytechnic Unit 3
<?php Output:
$str="oHello"; Hell
echo trim($str,"o")."<br>"; Hello
$str=" Hello ";
echo trim($str);
?>

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

11 Dept: CE DWPD (3350702) Twincle


Kalyan Polytechnic Unit 3
strpos
• Returns the position of the first 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 strpos("hello","e"); 1
echo strpos("hello","l"); 2
?>

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

12 Dept: CE DWPD (3350702) Twincle


Kalyan Polytechnic Unit 3
str_replace
• Replaces some characters in a string (case-sensitive).
• Syntax:- str_replace(find,replace,string,count)
✓ find: Required. Specifies the value to find
✓ replace: Required. Specifies the value to replace the value in find
✓ string: Required. Specifies the string to be searched
✓ count: Optional. A variable that counts the number of replacements
<?php Output:
echo str_replace("world","Rahul","Hello world!"); Hello Rahul!
?>

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

14 Dept: CE DWPD (3350702) Twincle


Kalyan Polytechnic Unit 3
rand
• Returns a random integer.
• Syntax: rand(min,max)
✓ min,max: Optional. Specifies the range the random number should lie within
• If this function is called without parameters, it returns a random integer between 0 and
RAND_MAX. (RAND_MAX depends on platform. For Windows value is 32768).
<?php Output:
echo rand()."<br>"; 18269
echo rand(40,500); 417
?>

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 )

15 Dept: CE DWPD (3350702) Twincle


Kalyan Polytechnic Unit 3
checkdate
• The checkdate() function returns true if the specified date is valid, and false otherwise.
• Syntax: checkdate(month,day,year)
✓ month, day, year: Required. Specifies the month, day and year.
• A date is valid if: month is between 1 to 12, day is within the allowed number of days for the
particular month, year is between 1 to 32767.
<?php Output:
var_dump(checkdate(2,29,2003)); boolean false
var_dump(checkdate(2,29,2004)); boolean true
?>

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

16 Dept: CE DWPD (3350702) Twincle

You might also like