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

Web Technologies 2: Arrays & Functions

This document discusses arrays and functions in PHP. It covers how to create and access different types of arrays, such as indexed arrays, associative arrays, and multidimensional arrays. It also discusses built-in PHP functions for working with arrays, such as count(), is_array(), and print_r(). The document then discusses user-defined functions in PHP and how they can be created to perform specific tasks. Functions allow programmers to reuse code and make their programs more organized and readable.

Uploaded by

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

Web Technologies 2: Arrays & Functions

This document discusses arrays and functions in PHP. It covers how to create and access different types of arrays, such as indexed arrays, associative arrays, and multidimensional arrays. It also discusses built-in PHP functions for working with arrays, such as count(), is_array(), and print_r(). The document then discusses user-defined functions in PHP and how they can be created to perform specific tasks. Functions allow programmers to reuse code and make their programs more organized and readable.

Uploaded by

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

WEB TECHNOLOGIES 2

Arrays & Functions


Lec5

Mohammed 1
PHP arrays
• An array stores multiple values in one single
variable.

• An array is a special variable, which can hold


more than one value at a time.
• An array in PHP is a type of data structure.
• If you have a list of items :
– a list of car names, for example storing variables
should look like :
– $cars1 = "Volvo";
– $cars2 = "BMW";
– $cars3 = "Toyota";
2
Create an Array in PHP
• The array() function is used to create an array.
– array(
– key => value,
– key2 => value2,
– key3 => value3,
– ...
–)
• The comma after the last array element is
optional and can be omitted.
• The key can either be an <?php $array = array(
"foo" => "bar",
int or a string. The value
-100 => 100,
can be of any type. 3
);?>
Create an Array in PHP
• The key is optional. If it is not specified, PHP will use
the increment of the largest previously used int key.
• It is possible to specify the key only for some
elements and leave it out for others
<?php array(4) {
$array = array( [0]=>
"a", string(1) "a"
"b", [1]=>
6 => "c", string(1) "b"
"d", [6]=>
); string(1) "c"
var_dump($array); [7]=>
?> string(1) "d"} 4
Create an Array in PHP
• A short array syntax exists which replaces
array() with []. <?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
// Using the short array syntax
$array = [
"foo" => "bar",
"bar" => "foo",
];
?> 5
Create an Array in PHP
• Alternative way:
– If $array doesn't exist yet or is set to null or
false, it will be created.
– $arr[key] = value;
– $arr[] = value;
• Always use quotes around a string literal
array index.
– $foo['bar'] is correct,
– $foo[bar] is not.
• Do not quote keys which are constants or
variables
Note: As of PHP 8.1.0, creating a new array
from false value is deprecated. 6
Array types
• In PHP, there are three types of arrays:
– Indexed arrays
• Arrays with a numeric index
– Associative arrays
• Arrays with named keys
– Multidimensional arrays
• Arrays containing one or more arrays

7
Indexed arrays
• Keeps track of these data items by using
sequential numbers.

• The index is an integer data type.


• Example :
– $grades = array(66, 72, 89);
– $students = array(‘ali’, ‘moh’,’ahmed’);

• The index begins from 0


– $average = ($grades[0]) ;//Output is 66

8
Associative arrays
• A string value index is used to look up or
provide a cross-reference to the data
value.
• Example :
$stuff = array("php" => "moh",
"html" => "ahmed");

9
Associative arrays
• Adding an Associative Array Item:
– $stuff ["css"] = "ali";

• Deleting an Associative Array Item:


– unset($stuff ["html"]);

10
Multidimensional arrays
• A multidimensional array is an array
containing one or more arrays.

• PHP supports multidimensional arrays


that are two, three, four, five, or more levels
deep. However, arrays more than three
levels deep are hard to manage for most
people.

11
Multidimensional arrays
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
); <?php
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>";?> 12
Accessing array elements
• Array elements can be accessed using the
array[key] syntax.
– <?php
– $array = array(
– "foo" => "bar"
– );
– var_dump($array["foo"]);
– ?>

13
Looping Through an Array:For
• $grades = array(66, 72, 89);
$sum = 0;
for (i=0; i < count(grades); i++)
$sum += $grades[i];
average = $sum/count(grades);

14
Looping Through an Array :foreach

• By using foreach function


<?php
$stuff = array("name" => "moh",
"course" => "PHP");

foreach($stuff as $k => $v ) {
//foreach ($stuff as $stf) for only value
echo "Key=",$k," Val=",$v,"\n";
}
?> Key=name Val=moh
Key=course Val=PHP 15
Array functions
• The count() Function:
– The count() function is used to return the
length (the number of elements) of an array:
– echo count($cars);

• array_search()
– Searches an array for a given value and
returns the key

16
Array functions
• count($ar) - How many elements in an array
• is_array($ar) - Returns TRUE if a variable is an array
• isset($ar['key']) - Returns TRUE if key is set in the array
• sort($ar) - Sorts the array values (loses key)
• ksort($ar) - Sorts the array by key
• asort($ar) - Sorts array by value, keeping key association
• shuffle($ar) - Shuffles the array into random order
• array_sum() - Sum numerical values in the array.
• array_pop( ) : Remove an item from the end of an array.
• array_push( ) : Add an item to the end of an array.

17
Example
$arr = array();
Outputs :
$arr["name"] = "moh";
Count: 2
$arr["course"] = "PHP";
$arr Is an array
print "Count: " . count($arr) . "\n";
name is set
if ( is_array($arr) ) {
addr is not set
echo '$arr Is an array' . "\n";
} else {
echo '$arr Is not an array' . "\n";
}
echo isset($arr['name']) ? "name is set\n" : "name is
not set\n";
echo isset($arr['addr']) ? "addr is set\n" : "addr is not
set\n"; 18
Arrays and Strings

$inp = "This is a sentence with seven


words"; Array(
$temp = explode(' ', $inp); [0] => This
print_r($temp); [1] => is
[2] => a
[3] => sentence
[4] => with
[5] => seven
[6] => words
)
19
Array operators
• Union $x + $y
– Union of $x and $y

• Equality $x == $y
– Returns true if $x and $y have the same key/value pairs

• Identity $x === $y // !==


– Returns true if $x and $y have the same key/value pairs
in the same order and of the same types

• Inequality $x != $y
– Returns true if $x is not equal to $y

20
Print_r
Outputs :
Array
<?php (
$x = array ('x' => 'Dept', [x] => Dept
'y' => 'Employee', [y] => Employee
'z' => array ('a', 'b', 'c')); [z] => Array
print_r ($x); (
?> [0] => a
[1] => b
[2] => c
)
) 21
FUNCTIONS

22
Functions
• The real power of PHP comes from its functions.

• Functions offer the ability for programmers to group


together program code that performs specific task or
function into a single unit that can be used repeatedly
throughout a program.

• Functions can accept data in the form of arguments


and can return results.
• Function names follow the same rules as other labels
in PHP
– A valid function name starts with a letter or underscore,
followed by any number of letters, numbers, or underscores.

23
Functions
• PHP does not support function
overloading

• Function names are case-insensitive


• Two types of functions in php :
– Built-in functions
– User defined functions

24
PHP Built-in Functions

• abs() Function: Returns the absolute


value of a number.
• sqrt( ) Function: Take the square root of a
single numerical argument.
• round( ) Function: Returns the number
rounded up or down to the nearest integer.

25
PHP Built-in Functions
• is_number( ) Function: Testing whether a
variable is a valid number or numeric string.
It returns true or false.

• rand( ) Function. Generate a random


number.

• date( ) Function. Determine the current


date and time.

26
PHP User Defined Functions
• Functions are defined using the function
statement.
• Syntax :
function function_name(parameters, arguments)
{
command block
}
function printName($name) {
• echo (“<HR> Your Name is <B><I>”);
echo $name;}
printName("mohammed" ); 27
Functions
• Returning Results:
function cube($number) {
$result = $number * $number * $number;
return $result;
}
$y = cube(3);

28
Functions
• In PHP Function, arguments may be used
to transfer information to functions. A
variable is the same as an argument.

• Parameters are the information or


variables contained within the function's
parenthesis. These are used to store the
values that can be executed at runtime.

29
Passing Arguments By Reference
• Arguments are generally passed by value in
PHP, which ensures that the function uses a
copy of the value and the variable passed
into the function cannot be modified.

• Changes to the argument modify the


variable passed in when a function
argument is passed by reference. The &
operator is used to convert a function
argument into a reference.

30
Passing Arguments By Reference
<?php
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str; // outputs 'This is a string, and
something extra.'
?>
31
Optional Arguments & default
values
function OutputLine($text, $size=3, $color =
“black”)
{
echo “<font color = $color size = $size>
$text </font>
}

32
Functions within functions
<?php
function fun1()
{
function fun2()
{
echo "I don't exist until fun1() is called.\n";
}
}
/* We can't call fun2() yet since it doesn't exist. */
fun1();
/* Now we can call fun2(), fun1()'s processing has
made it accessible. */

33
Recursive functions

<?php
function recursion($a)
{
if ($a < 20) {
echo "$a\n";
recursion($a + 1);
}
}
?>

34
• For arrays
– https://www.php.net/manual/en/language.
types.array.php
• For functions
– https://www.php.net/manual/en/language.
functions.php

35
Any Questions?

36

You might also like