0% found this document useful (0 votes)
105 views

UNIT-3 - Working With Arrays and Functions

This document provides information about arrays in PHP. It discusses how to create arrays using the array() function or array identifier. It describes indexed, associative, and multidimensional arrays. Functions for sorting arrays like sort(), rsort() are also covered. The document shows how to define user functions in PHP and pass parameters to functions. In summary, the key topics covered are array types in PHP, creating and accessing array elements, viewing array structure, adding elements, sorting arrays, and user defined functions.

Uploaded by

ankit bose
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
105 views

UNIT-3 - Working With Arrays and Functions

This document provides information about arrays in PHP. It discusses how to create arrays using the array() function or array identifier. It describes indexed, associative, and multidimensional arrays. Functions for sorting arrays like sort(), rsort() are also covered. The document shows how to define user functions in PHP and pass parameters to functions. In summary, the key topics covered are array types in PHP, creating and accessing array elements, viewing array structure, adding elements, sorting arrays, and user defined functions.

Uploaded by

ankit bose
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

DIPLOMA IN COMPUTER ENGINEERING

SEMESTER : 5
UNIT : 3

DYNAMIC WEB PAGE DEVELOPMENT


(3350702)

Prepared By : Miss Dhara H. Wagh


Lecturer in Computer Engineering Department

Government Polytechnic Gandhinagar


Array in PHP
 Arrays are complex variables that allow us to store more than one value or a
group of values under a single variable name. Let's suppose you want to
store colors in your PHP script.
<?php
$color1 = "Red";
$color2 = "Green";
$color3 = "Blue";
?>
 But what, if you want to store the states or city names of a country in
variables and this time this not just three may be hundred. It is quite hard,
boring, and bad idea to store each city name in a separate variable. And here
array comes into play.
Create an Array in PHP : array() function
1. In PHP, the array() function is used to create an array: array();
$variable_name = array(n => value, …);
 $variable_name is the name of array variable
 “[n]” is the access index number of the element
 “value” is the value assigned to the array element.
Example :
$cars = array("Volvo", "BMW", "Toyota");
Create an Array in PHP : Using Array identifier
2. Using Array identifier
$variable_name[n] = value;
Example :
$cars [0]="Volvo“;
$cars [1]="BMW“;
$cars [2]="Toyota“;
Types of Arrays in PHP

Indexed array/
Numeric Array
An array with a numeric key.

Associative array An array where each key has its own specific
descriptive names key .

Multidimensional
array
An array containing one or more arrays within itself.
Indexed Arrays

 An indexed or numeric array stores each array element with a numeric index.
 Values are stored and accessed in linear fashion.
 Array index is represented by number which starts from 0. We can store number,
string and object in the PHP array. All PHP array elements are assigned to an index
number by default.
 1st way: $season=array("summer","winter","spring","autumn");

 2nd way: $season[0]="summer";


$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
Indexed Arrays

 Example :
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2]
and $season[3]";
foreach($season as $a)
{
echo “$a <br>”;
}
Associative Arrays

 Associative array will have string as index so that you can establish a strong association
between key and values.
 Associative arrays are arrays that use named keys that you assign to them.
 Syntax : <?php
$variable_name['key_name'] = value;
$variable_name = array('keyname' => value);
?>
 $variable_name is the name of array the variable
 ['key_name'] is the access index of the element
 “value” is the value assigned to the array element.
Associative Arrays
 To store the salaries of employees in an array, a numerically indexed array would not be
the best choice. Instead, we could use the employees names as the keys in our associative
array, and the value would be their respective salary.
 Example :<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
foreach($salary as $k=>$v)
{ echo "Key is ".$k." Value :".$v;
echo "<br>";
}
?>
Multidimesional Arrays

 A multi-dimensional array each element in the main array can also be an


array. And each element in the sub-array can be an array, and so on. Values in
the multi-dimensional array are accessed using multiple index.
 A multidimensional array is an array containing one or more arrays.
 It allows you to store tabular data in an array. PHP multidimensional array
can be represented in the form of matrix which is represented by row *
column.
 PHP support two , three and more dimesional levels arrays but they are hard
to manage.
Multidimesional Arrays in PHP

<?php
$cars = array ( array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
Multidimesional Arrays in PHP: for
<?php $cars = array ( array("Volvo",22,18), array("BMW",15,13),
array("Saab",5,2), array("Land Rover",17,15)
);
for ($row = 0; $row < 4; $row++)
{ echo "<p><b>Row number $row</b></p>"; echo "<ul>";
for ($col = 0; $col < 3; $col++)
{
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
Viewing Array Structure and Values

 The structure and values of any array can be display using one of two statements —
var_dump() or print_r()
 The print_r() function prints the information about a variable in a more human-readable
way.
 Syntax : print_r(variable [, return]);
<?php
$a = array("red", "green", "blue");
print_r($a); echo "<br>";
$b = array("Peter"=>"35", “Smith"=>"37", "Joe"=>"43");
print_r($b);
?>
print_r() Function

 The structure and values of any array can be display using one of two statements —
var_dump() or print_r()
 The print_r() function prints the information about a variable in a more human-readable
way.
 Syntax : print_r($variablename);
<?php
$a = array("red", "green", "blue");
print_r($a); echo "<br>";
$b = array("Peter"=>"35", “Smith"=>"37", "Joe"=>"43");
print_r($b);
?>
Adding Elements to arrays
 You can add automatically indexed elements usng [ ] operator.
 Example:
<?php
$myarray=array();
$myarray [ ] =‘Good Morning’;
$myarray[ ]=‘Have a nice Day’;
$myarray[ ]=‘Today is Tuesday’;

print_r($myarray);
?>
Array Sorting Functions

Function Name Description

sort() sort arrays in ascending order

rsort() sort arrays in descending order

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


Array Functions

Function Name Description

sort() sort arrays in ascending order

rsort() sort arrays in descending order

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


Array Functions

Function Name Description

sort() sort arrays in ascending order

rsort() sort arrays in descending order

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


User Defined Functions
 PHP User-defined Functions
 We can declare and call user-defined functions easily. Let's see the
syntax to declare user-defined functions.

 Syntax :
function functionname()
{
//code to be executed
}
User Defined Functions

Example :
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>
User Defined Functions

Example :
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
User Defined Functions

Example :
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
Parameter Passing Defined Functions
 PHP Parameterized functions are the functions with parameters. You
can pass any number of parameters inside a function. These passed
parameters act as variables inside your function.

 They are specified inside the parentheses, after the function name.

 The output depends upon the dynamic values passed as the parameters
into the function.
Parameter Passing Defined Functions
Example :<?php //Adding two numbers
function add($x, $y)
{ $sum = $x + $y;
echo "Sum of two numbers is = $sum <br><br>";
}
add(467, 943);
//Subtracting two numbers
function sub($x, $y)
{ $diff = $x - $y;
echo "Difference between two numbers is = $diff";
}
sub(943, 467);
?>
Call by Value

 PHP allows you to call function by value and reference both. In case of
PHP call by value, actual value is not modified if it is modified inside the
function.
Example :
<?php function adder($str2)
{ $str2 .= 'Call By Value'; }
$str = 'Hello ';
adder($str);
echo $str;
?>
Call by Reference

 In case of PHP call by reference, actual value is modified if it is modified


inside the function. In such case, you need to use & (ampersand) symbol
with formal arguments. The & represents reference of the variable.
Example : <?php
function adder(&$str2)
{ $str2 .= 'Call By Reference'; }
$str = 'This is ';
adder($str);
echo $str;
?>
Default Argument Values Function

 You can set a parameter to have a default value if the function's caller doesn't
pass it.
Example : <?php
function printMe($param = NULL)
{ print $param; }

printMe("This is test");
printMe();
?>
Dynamic Function Calls

 It is possible to assign function names as strings to variables and then treat


these variables exactly as you would the function name itself
Example : <?php
function sayHello() {
echo "Hello<br />";
}

$function_holder = "sayHello";
$function_holder();
?>
Dynamic Function Calls

 It is possible to assign function names as strings to variables and then treat


these variables exactly as you would the function name itself
Example : <?php
function sayHello() {
echo "Hello<br />";
}

$function_holder = "sayHello";
$function_holder();
?>
String Function

 String functions allow you to manipulate the string in various ways.


 You can perform different operations on string using these functions.
 Different string functions in PHPare asbelow :

 Ltrim  Chr
 Rtrim  Ord
 Trim  Chr
 Substr  Ord
 Strcmp  Strtolower
 strrev  Strtoupper
Date Functions

 PHP date() function shows day, month and year altogether. Date and time
are stored in computer in UNIX Timestamp format. It calculates time in
number of seconds on GMT (greenwich mean time) i.e started from January
1, 1970, 00:00:00 GMT.
 Syntax : string date ( string $format [, int $timestamp = time() ] )
 Date function allows you to display date and time in different format and
manipulate it.
 Different date functions in PHP are as below:
date
getdate
checkdate
Date Functions
 getdate : returns an array with date, time information for an unix timestamp.
 Syntax: getdate(timestamp)
 Returns an associative array with information related to the timestamp:
 [seconds] - seconds
 [minutes] - minutes
 [hours] - hours
 [mday] - day of the month
 [wday] - day of the week (0=Sunday, 1=Monday,...)
 [mon] - month
 [year] - year
 [yday] - day of the year
 [weekday] - name of the weekday
 [month] - name of the month
Date Functions

• Example:
<?php
print_r(getdate());
?>
Date Functions
• checkdate :check the validity of a givendate.
• Syntax: Boolean checkdate ( int month , int day, int year)

• Example:
<?php
echo checkdate(2,28,2016).“<br/>”;
echo checkdate(28,2,2016).“<br/>”;
?>
THANK YOU

You might also like