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

PHP Unit-4

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

PARUL UNIVERSITY - Faculty of IT & Computer Science

BCA, B.Sc. (IT), IMCA Sem-2


Open Source Technology using PHP (05101204)
Unit-4
PHP Arrays and Functions
PHP Array
[1] PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple
values of similar type in a single variable.

Advantage of PHP Array


Less Code: We don't need to define multiple variables.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
Sorting: We can sort the elements of array.

[2] PHP Array Types


There are 3 types of array in PHP.
1. Indexed Array
2. Associative Array
3. Multidimensional Array

(1) PHP Indexed Array


PHP 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.
There are two ways to define indexed array:

1st way:
$season=array("summer","winter","spring","autumn");

2nd way:
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";

Example
File: array1.php
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>

Output:
Season are: summer, winter, spring and autumn

Faculties: Ravi Nimavat, Sohil Parmar, Hardik Parmar Page 57


PARUL UNIVERSITY - Faculty of IT & Computer Science
BCA, B.Sc. (IT), IMCA Sem-2
Open Source Technology using PHP (05101204)

File: array2.php
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Season are: summer, winter, spring and autumn
(2) PHP Associative Array
We can associate name with each array elements in PHP using => symbol.
There are two ways to define associative array:
1st way:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");

2nd way:
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";

Example
File: arrayassociative1.php
<?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/>";
?>
Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000

File: arrayassociative2.php
<?php
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000

Faculties: Ravi Nimavat, Sohil Parmar, Hardik Parmar Page 58


PARUL UNIVERSITY - Faculty of IT & Computer Science
BCA, B.Sc. (IT), IMCA Sem-2
Open Source Technology using PHP (05101204)
(3) PHP Multidimensional Array
PHP multidimensional array is also known as array of 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.
Definition
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);

PHP Multidimensional Array Example


Let's see a simple example of PHP multidimensional array to display following tabular data.
In this example, we are displaying 3 rows and 3 columns.
Id Name Salary
1 sonoo 400000
2 john 500000
3 rahul 300000
File: multiarray.php
<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);

for ($row = 0; $row < 3; $row++) {


for ($col = 0; $col < 3; $col++) {
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000

Faculties: Ravi Nimavat, Sohil Parmar, Hardik Parmar Page 59


PARUL UNIVERSITY - Faculty of IT & Computer Science
BCA, B.Sc. (IT), IMCA Sem-2
Open Source Technology using PHP (05101204)
[3] Loop Through an Indexed Array and Associative Arrays

Loop Through an Indexed Array


To loop through and print all the values of an indexed array, you could use a for loop, like
this:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?>
Output:
Volvo
BMW
Toyota

Loop Through an Associative Array


To loop through and print all the values of an associative array, you could use a foreach loop,
like this:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Output:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43

[4] Array Lib. Functions


(1) count() - Returns the number of elements in an array.
Syntax: count($array)
Example:
$fruits = array("apple", "banana", "orange");
$count = count($fruits);
echo "The number of elements in the array is: " . $count;

Output: The number of elements in the array is: 3

Faculties: Ravi Nimavat, Sohil Parmar, Hardik Parmar Page 60


PARUL UNIVERSITY - Faculty of IT & Computer Science
BCA, B.Sc. (IT), IMCA Sem-2
Open Source Technology using PHP (05101204)
(2) current() - Returns the current element in an array.
Syntax: current($array)

Example:
$fruits = array("apple", "banana", "orange");
echo "The current element in the array is: " .
current($fruits);

Output: The current element in the array is: apple

(3) next() - Advances the internal pointer of an array by one and returns the new current
element.
Syntax: next($array)

Example:
$fruits = array("apple", "banana", "orange");
echo "The next element in the array is: " . next($fruits);

Output: The next element in the array is: banana

(4) previous() - Rewinds the internal pointer of an array by one and returns the previous
element.
Syntax: prev($array)

Example:
$fruits = array("apple", "banana", "orange");
end($fruits); // move the pointer to the end of the array
echo "The previous element in the array is: " . prev($fruits);

Output: The previous element in the array is: banana

(5) end() - Moves the internal pointer of an array to the last element and returns it.
Syntax: end($array)

Example:
$fruits = array("apple", "banana", "orange");
echo "The last element in the array is: " . end($fruits);

Output: The last element in the array is: orange


(6) sort() - Sorts an array in ascending order.
Syntax: sort($array)

Example:
$fruits = array("orange", "apple", "banana");
sort($fruits);
print_r($fruits);

Faculties: Ravi Nimavat, Sohil Parmar, Hardik Parmar Page 61


PARUL UNIVERSITY - Faculty of IT & Computer Science
BCA, B.Sc. (IT), IMCA Sem-2
Open Source Technology using PHP (05101204)
Output:
Array
(
[0] => apple
[1] => banana
[2] => orange
)

(7)rsort() - Sorts an array in descending order.


Syntax: rsort($array)

Example:
$fruits = array("orange", "apple", "banana");
rsort($fruits);
print_r($fruits);

Output:
Array
(
[0] => orange
[1] => banana
[2] => apple
)

(8) assort() - Sorts an associative array by its values in ascending order, while maintaining
the key-value associations.
Syntax: asort($array)

Example:
$age = array("Peter"=>35, "John"=>25, "Mary"=>30);
asort($age);
print_r($age);
Output:

Array
(
[John] => 25
[Mary] => 30
[Peter] => 35
)

(9) arsort() - Sorts an associative array by its values in descending order, while maintaining
the key-value associations.
Syntax: arsort($array)

Example:
$age = array("Peter"=>35, "John"=>25, "Mary"=>30);
arsort($age);
print_r($age);

Faculties: Ravi Nimavat, Sohil Parmar, Hardik Parmar Page 62


PARUL UNIVERSITY - Faculty of IT & Computer Science
BCA, B.Sc. (IT), IMCA Sem-2
Open Source Technology using PHP (05101204)
Output:
Array
(
[Peter] => 35
[Mary] => 30
[John] => 25
)

(10) array_merge() - Merges two or more arrays into a single array.


Syntax: array_merge($array1, $array2, $array3, ...)

Example:
$fruits1 = array("apple", "banana");
$fruits2 = array("orange", "kiwi");
$fruits3 = array("grape", "mango");
$all_fruits = array_merge($fruits1, $fruits2, $fruits3);
print_r($all_fruits);

Output:
Array
(
[0] => banana
[1] => orange
[2] => kiwi
)

(11) array_unique() (contd.) - Removes duplicate values from an array.


Syntax: array_unique($array, $sorting_type)
Example:
$fruits = array("apple", "banana", "kiwi", "banana", "orange",
"kiwi");
$unique_fruits = array_unique($fruits);
print_r($unique_fruits);
Output
Array
(
[0] => apple
[1] => banana
[2] => kiwi
[4] => orange
)
(12) array_unshift() - Adds one or more elements to the beginning of an array.
Syntax: array_unshift($array, $value1, $value2, ...)

Example:
$fruits = array("banana", "orange");
array_unshift($fruits, "apple", "kiwi");
print_r($fruits);

Faculties: Ravi Nimavat, Sohil Parmar, Hardik Parmar Page 63


PARUL UNIVERSITY - Faculty of IT & Computer Science
BCA, B.Sc. (IT), IMCA Sem-2
Open Source Technology using PHP (05101204)
Output:
Array
(
[0] => apple
[1] => kiwi
[2] => banana
[3] => orange
)

(13)array_keys() - Returns all the keys or a subset of the keys of an array.


Syntax: array_keys($array, $search_value, $strict)

Example:
$age = array("Peter"=>35, "John"=>25, "Mary"=>30);
$keys = array_keys($age);
print_r($keys);
Output
Array
(
[0] => Peter
[1] => John
[2] => Mary
)
(14) array_key_exists() - Checks if a given key exists in an array.
Syntax: array_key_exists($key, $array)

Example:
$age = array("Peter"=>35, "John"=>25, "Mary"=>30);
if (array_key_exists("John", $age)) {
echo "John is in the array.";
} else {
echo "John is not in the array.";
}

Output
John is in the array.

(15) array_push() - Adds one or more elements to the end of an array.


Syntax: array_push($array, $value1, $value2, ...)

Example:
$fruits = array("apple", "banana");
array_push($fruits, "orange", "kiwi");
print_r($fruits);

Faculties: Ravi Nimavat, Sohil Parmar, Hardik Parmar Page 64


PARUL UNIVERSITY - Faculty of IT & Computer Science
BCA, B.Sc. (IT), IMCA Sem-2
Open Source Technology using PHP (05101204)
Output
Array
(
[0] => apple
[1] => banana
[2] => orange
[3] => kiwi
)

(16) array_pop() - Removes and returns the last element of an array.


Syntax: array_pop($array)

Example:
$fruits = array("apple", "banana", "orange");
$last_fruit = array_pop($fruits);
print_r($fruits);
echo "The last fruit was: " . $last_fruit;

Output

Array
(
[0] => apple
[1] => banana
)
The last fruit was: orange

(17) array_multisort() - Sorts multiple arrays or a multi-dimensional array.


Syntax: array_multisort($array1, $sorting_order1, $sorting_type1, $array2, $sorting_order2,
$sorting_type2, ...)

Example:
$age = array(35, 25, 30);
$name = array("Peter", "John", "Mary");
array_multisort($age, SORT_DESC, SORT_NUMERIC, $name,
SORT_ASC,

(18) array_search() - Searches an array for a given value and returns the corresponding key
if successful.
Syntax: array_search($value, $array, $strict)
Example:
$fruits = array("apple", "banana", "kiwi", "orange");
$key = array_search("kiwi", $fruits);
echo "The key of kiwi is: " . $key;
Output
The key of kiwi is: 2

Faculties: Ravi Nimavat, Sohil Parmar, Hardik Parmar Page 65


PARUL UNIVERSITY - Faculty of IT & Computer Science
BCA, B.Sc. (IT), IMCA Sem-2
Open Source Technology using PHP (05101204)
PHP Functions
[1] PHP Functions
In addition to the built-in functions, PHP also allows you to define your own functions to
perform specific tasks. User-defined functions can be created using the function keyword,
followed by the function name, parameters, and function body enclosed in curly braces.

Here's an example of a user-defined function that takes two parameters and returns their sum:
function add($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
In this example, the function is named add and accepts two parameters $num1 and $num2.
The function then calculates the sum of the two numbers and returns the result using the
return keyword.

To call the add function and pass it two numbers as arguments, you would use the following
code:
$result = add(2, 3);
echo $result; // Outputs 5

This would output 5 because the add function adds the two arguments 2 and 3 and returns the
result.
You can define any number of user-defined functions to perform specific tasks and make
your code more modular and easier to read. When creating user-defined functions, it's
important to choose descriptive names and to ensure that the function performs only one task
to keep your code organized and maintainable.

[2] Functions with arguments


PHP functions can accept one or more arguments (also known as parameters) that are passed
to the function when it is called. These arguments allow you to pass data to the function and
perform specific tasks based on that data.

Here's an example of a PHP function that accepts two arguments and returns their product:
function multiply($num1, $num2) {
$product = $num1 * $num2;
return $product;
}

In this example, the multiply() function accepts two arguments $num1 and $num2. It then
multiplies these two numbers and returns the product using the return keyword.

To call the multiply() function and pass it two numbers as arguments, you would use the
following code:

Faculties: Ravi Nimavat, Sohil Parmar, Hardik Parmar Page 66


PARUL UNIVERSITY - Faculty of IT & Computer Science
BCA, B.Sc. (IT), IMCA Sem-2
Open Source Technology using PHP (05101204)
$result = multiply(2, 3);
echo $result; // Outputs 6

This would output 6 because the multiply() function multiplies the two arguments 2 and 3
and returns the result.

You can pass any number of arguments to a PHP function, and the function can use these
arguments to perform specific tasks. It's important to ensure that the function's parameters
match the data types and formats of the arguments that will be passed to it to avoid errors and
unexpected results.

[3] Miscellaneous Functions


(1) define(): Defines a constant with a specified name and value. The value cannot be
changed during the script's execution. Here's an example:
define('PI', 3.14);
echo PI; // Outputs 3.14

(2) const: Defines a constant with a specified name and value. The value cannot be changed
during the script's execution. Here's an example:
const MAXIMUM_VALUE = 100;
echo MAXIMUM_VALUE; // Outputs 100

(3) include(): Includes and evaluates the specified file. If the file is not found, it generates a
warning and continues execution. Here's an example:
include 'myFile.php';

(4) require(): Includes and evaluates the specified file. If the file is not found, it generates a
fatal error and stops execution. Here's an example:
require 'myFile.php';

(5) die() / exit(): Terminates the script's execution and outputs a message. Here's an example:
if ($value < 0) {
die('Error: Value must be positive.');
}
In the above example, if the condition is true, the script will terminate and output the error
message.

These functions can be used in various ways to accomplish specific tasks in PHP scripts. It's
important to use them correctly and to understand their specific behaviors to avoid errors and
unexpected results.

Faculties: Ravi Nimavat, Sohil Parmar, Hardik Parmar Page 67

You might also like