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

Lec 3- Php functions_arrays

The document provides an overview of PHP functions and arrays, detailing built-in and user-defined functions, function parameters, return values, variable scope, and anonymous functions. It also covers array creation, accessing and updating arrays, associative arrays, and various array functions such as merging, sorting, and reducing arrays. Additionally, it includes examples and references for further learning.

Uploaded by

gtas8626
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)
7 views

Lec 3- Php functions_arrays

The document provides an overview of PHP functions and arrays, detailing built-in and user-defined functions, function parameters, return values, variable scope, and anonymous functions. It also covers array creation, accessing and updating arrays, associative arrays, and various array functions such as merging, sorting, and reducing arrays. Additionally, it includes examples and references for further learning.

Uploaded by

gtas8626
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/ 22

PHP : Functions & Arrays

MAGED SHEGHDARA
Functions
➢ PHP has more than 1000 built-in functions, and in addition you can create your own custom
functions.

➢ A function is a block of statements that can be used repeatedly in a program.

➢ A function will not execute automatically when a page loads.

➢ A function will be executed by a call to the function.

➢ A user-defined function declaration starts with the keyword function, followed by the name of
the function and parentheses

2
Functions
function myMessage () {
echo "Hello world“ ;
}

To call the function, just write its name followed by parentheses :) (

function myMessage () {
echo "Hello world“ ;
}

myMessage();

3
Function Parameters
➢ You can pass information to a function using parameters. Parameters are specified within the
parentheses when defining the function.

<?php
function greetUser($name) {
echo "Hello, $name!";
}

greetUser("John");
?>

4
Return Values
➢ Functions can also return values using the return statement.

<?php
function add($a, $b) {
$sum = $a + $b;
return $sum;
}

$result = add(5, 3);


echo "Result: $result";
?>

5
Variable Scope
➢ Variables defined inside a function have local
<?php
scope, meaning they can only be accessed within
the function. Variables defined outside of any
function have global scope and can be accessed $globalVar = 10;
from anywhere in the script.
function showGlobalVar() {
➢ It's important to note that global variables global $globalVar;
cannot be directly accessed inside a function. To echo "Global Variable: $globalVar";
use a global variable inside a function, you need to }
use the global keyword
showGlobalVar();
?>

6
Anonymous Functions
➢ Anonymous functions, also known as closures, allow you to create functions without naming
them. They are handy for tasks like callback functions.

<?php
$addition = function ($a, $b) {
return $a + $b;
};

$result = $addition(2, 3);


echo "Result: $result";
?>

7
Arrow Functions (short closures)
➢They are mainly used for simple, single-expression functions
➢Arrow functions have the basic form
fn (argument_list) => expr.
➢Unlike anonymous functions, arrow functions cannot have a void return type declaration and
multiple statement

$addition = fn($a, $b) => $a + $b;

// Usage
$result = $addition(2, 3);
echo "Result: $result"; // Outputs: Result: 5

8
Arrays
➢ An array allow the programmer to collect a related elements together in a single variable.

➢ Unlike most programming languages, in PHP each element in the array is KEY/VALUE pair.

➢ The array keys are integers start at 0 and go up or strings. On the other hand, the array values
can take any type supported by PHP.

9
Create Arrays
➢You can create arrays by using the array() function:
$days = array(); //declares an empty array named days
$days = []; //alternative syntax
➢To define the contents of an array as strings for the days of the week:
$days = array("Mon","Tue","Wed","Thu","Fri");
$days = ["Mon","Tue","Wed","Thu","Fri"]; // alternate syntax
➢In these examples, because no keys are explicitly defined for the array, the default key values are
0, 1, 2,. . . , n.
➢You do not have to provide a size for the array: arrays are dynamically sized as elements are added
to them.

10
Accessing & Updating an Array
➢Use square brackets to access the elements of the array:
echo "Value at index 1 is ". $days[1]; // index starts at zero
➢Define the array elements individually using this same square bracket notation:
$days = array();
$days[0] = "Mon";
$days[1] = "Tue";
$days[2] = "Wed";
// also alternate approach
$daysB = array();
$daysB[] = "Mon";
$daysB[] = "Tue";
$daysB[] = "Wed";

11
Note
➢In PHP, arrays are dynamic, that is, they can grow or shrink in size. An element can be added to
an array simply by using a key/index that hasn’t been used.
$days[5] = "Sat";
➢If the key of the above example exists then it will replace the old value of this key with the new
one.
➢As an alternative to specifying the index, a new element can be added to the end of any array
using the following technique:
$days[ ] = "Sun";
➢The advantage to this approach is that we don’t have to worry about skipping an index key.

12
Accessing & Updating an Array (Con’t)
➢You can iterate through the array elements using:
// while loop
$i=0;
while ($i < count($days))
{ echo $days[$i]; $i++; }
// do while loop
$i=0;
do { echo $days[$i] ; $i++; } while ($i < count($days));
// for loop
for ($i=0; $i<count($days); $i++)
{ echo $days[$i] . "<br>"; }

13
Accessing & Updating an Array (Con’t)
// foreach
$cars = array("Volvo", "BMW", "Toyota");
foreach($cars as $c)
{ echo $c; }

// foreach: iterating through the values AND the keys


foreach ($forecast as $key => $value)
{ echo "day " . $key . "=" . $value; }

➢For debugging purpose use the function print_r() to output the contents of the array.

14
Remove Array Item
➢To remove an existing item from an array, you can use the unset() function.
$cars = array("Volvo", "BMW", "Toyota");
unset($cars[1]);

➢If you want to remove more than one item:


unset($cars[1], $cars[2]);

15
Remove Array Item (Con’t)
➢array_splice — Remove a portion of the array and replace it with something else.

Syntax: array_splice(array, start, length, array)


$array = [1, 2, 3, 4, 5];
array_splice($array, 2, 2);
// $array is now [1, 2, 5]

16
Associate Arrays
➢If you use strings as KEYs in the array, in this case these arrays are referred to as associative
arrays.

17
Array Functions
➢To combine two arrays into a single, new array use array_merge() as follows:
$first = ['a', 'b', 'c'];
$second = ['x', 'y', 'z'];
$merged = array_merge($first, $second);

➢In addition, you can also leverage the spread operator (…) to combine arrays
$merged = [...$first, ...$second];

➢To reverse the order of elements in an array, use array_reverse() as follows:


$array = ['five', 'four', 'three', 'two', 'one', 'zero’];
$reversed = array_reverse($array);

18
Array Functions (Con’t)
➢ The elements in an array can be sorted in alphabetical or numerical order, descending or
ascending.
sort() - sort arrays in ascending order
rsort() - sort arrays in descending order
➢Example:
$numbers = array(4, 6, 2, 22, 11);
Sort($numbers);

19
Apply a Function to Every Element of an Array
➢To transform an array by applying a function to modify every element of the array in turn use
array_walk()
$values = range(2, 5);
array_walk($values, function(&$value, $key) {
$value *= $value;
});
print_r($values);
// Array
// (
// [0] => 4
// [1] => 9
// [2] => 16
// [3] => 25
// )

20
Reduce an Array
➢If you want to iteratively reduce a collection of values to a single value use array_reduce()
$values = range(0, 10);
$sum = array_reduce($values, function($carry, $item) {
return $carry + $item;
}, 0);
// $sum = 55
➢The callback function accepts two parameters. The first is the value you’re carrying over from
the last operation. The second is the value of the current item in the array over which you’re
iterating. The third argument is the initial value (optional)

21
References
https://www.php.net/manual/en/langref.php
https://www.php.net/manual/en/book.array.php
https://www.w3schools.com/php

22

You might also like