# Functions

# Built-in functions

  • PHP contains lots of built-in functions
  • We restrict ourselves to some useful array, string and date functions

# Array functions

Function Comment
in_array($value, $array) checks if a specified $value exists in an $array
asort($array) sort $array in ascending order and maintain index association
(important with associative arrays!)
arsort($array) sort $array in descending order and maintain index association
(important with associative arrays!)
ksort($array) Sort $array by key in ascending order
krsort($array) sort $array by key in descending order
array_push($array, $values) push one or more $values onto the end $array
array_unshift($array, $values) prepend one or more $values to the beginning of $array
implode($separator, $array) join $array elements with a $separator string
compact() create an array containing variables and their values

# String functions

Function Comment
strlen($string) returns the length of $string
strpos($haystack, $needle) returns the position of the string $needle in the string $haystack
ucfirst($string) returns a string in which the first letter of $string is capitalized
substr($string, $start, $length) returns a portion (with $length characters) of $string, starting from position $start
str_replace($search, $replace, $string) returns a string with all occurrences of $search in $string replaced by $replace
strtoupper($string) make $string and uppercase
strtolower($string) make $string and lowercase
ucwords($string) uppercase the first character of each word in $string
explode($delimiter, $string) returns an array of strings, each of which is a substring of $string and which are separated by $delimiter
number_format($number, $decimals, $decimalPoint, $thousandsSeparator) returns a string with a formatted version of $number, specified by the number of $decimals, the $decimalPoint and the $thousandsSeparator
str_starts_with($haystack, $needle) (PHP 8) determine if a $haystack starts with a given $needle
str_contains($haystack, $needle) (PHP 8) determine if a $haystack contains a given $needle
str_ends_with($haystack, $needle) (PHP 8) determine if a $haystack ends with a given $needle

# Date/time functions

Function Comment
mktime($hour,$minute,$second,$month,$day,$year) get Unix timestamp for a date
date("format", $timestamp) format a local time/date
time() return current Unix timestamp


 
 

 
 

 
 



<article>
    <?php
    $timestamp = mktime(0, 0, 0, 12, 25, 2022); //25-12-2022, 0u00
    echo "<p> Christmas 2022 (" . date("d/m/Y", $timestamp) . ") falls on a " . date("l", $timestamp) . "</p>\n";

    echo "<p> Now, we are " . date("D d-m-Y, H:i:s") . "<br>"
      . time() . " seconds have passed since January 1, 1970, 00:00:00 </p>\n";

    $within4weeks = mktime(0, 0, 0, date("m"), date("d") + 28, date("Y"));
    echo "<p> Within 4 weeks, we are " . date("l d F 'y", $within4weeks) . "</p>\n";
    ?>
</article>
1
2
3
4
5
6
7
8
9
10
11
12

Date functions

  • With the date("format", $timestamp) function, this $timestamp is converted into a readable format
    • Using date("format") - without timestamp - we get the current date/time on the server
    • Some format characters:
format character description values
d day of the month with leading zeros 01 - 31
D textual representation (three letters) of the day Mon - Sun
j day of the month without leading zeros 1 - 31
l full textual representation of the day Monday - Sunday
F full textual representation of the month January - December
m numerical representation of the month with leading zeros 01 - 12
M textual representation (three letters) of the month Jan - Dec
n numerical representation of the month without leading zeros 1 - 12
Y numerical representation (4 digits) of a year 1970, 2019
y numerical representation (2 digits) of a year 70, 19
h 12-hour format with leading zeros 01 - 12
H 24-hour format with leading zeros 00 - 23
i minutes with leading zeros 00 - 59
s seconds with leading zeros 00 - 59

REMARK

Probably, there is a time difference between the depicted time (on the server) and the local time, because the timezone on the server is incorrect. You can set the default timezone on the server to the correct timezone by adding the statement date_default_timezone_set('Europe/Brussels'), e.g. to the file shared/meta.php (included on every page).

# User-defined functions

  • Open course/user_defined_functions.php
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 


 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 


<?php
function writeMessage(): void
{
    echo "<p> We hope you like this PHP course! </p>\n";
}

function writePersonalMessage(string $name): void
{
    echo "<p> Dear $name, we hope you like this PHP course! </p>\n";
}

function writePersonalMessageWithDefault(string $name = 'Mr./Mrs.'): void
{
    echo "<p> Dear $name, we hope you like this PHP course! </p>\n";
}

function subtractReduction20(float $price): void
{
    $price *= 0.8;
}

function subtractReduction30(float &$price): void
{
    $price *= 0.7;
}

function average(float $number1, float $number2): float
{
    return ($number1 + $number2) / 2;
}
?>

<article>
    <?php
    writeMessage();
    writePersonalMessage('John');
    writePersonalMessageWithDefault('Jane');
    writePersonalMessageWithDefault();


    $price = 1000;
    subtractReduction20($price);
    echo "<p> Price with 20% reduction = " . $price . "</p>\n";

    $price = 1000;
    subtractReduction30($price);
    echo "<p> Price with 30% reduction = " . $price . "</p>\n";

    echo "<p> Average of 10 and 100 = " . average(10, 100) . "</p>\n";
    ?>
</article>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

User-defined functions

# Functions without parameters

  • A user-defined function (e.g. function writeMessage(): void) starts with the keyword function, followed by( ) and his return value :void
  • The function code should be placed between { }

# Functions with parameters

  • Put the parameters of a function between the round brackets, as in function writePersonalMessage(string $name): void
  • When a function with parameters is called (e.g. writePersonalMessage('John');), we need to supply arguments (the string 'John') to pass to the parameters ($name)
  • These parameters work like variables inside your function

# Default values for parameters

  • You can set a parameter to have a default value if no argument is passed to the function, as in writePersonalMessageWithDefault(string $name = 'Mr./Mrs.'): void

# By value versus by reference

  • By default, arguments are passed by value
    • This means that the original value of a variable is not changed when you pass it as an argument to a function in which it is changed. See e.g. function subtractReduction20(float $price): void
  • You can pass a variable to a function by reference, meaning that the original value can be changed in the function
    • In order to do so, precede the parameter in the function definition with &, as illustrated in
      subtractReduction30(float &$price): void

# Functions with return value

  • A function can return a value using the return statement, as illustrated in
    function average(float $number1, float $number2): float

# Short arrow function

  • A short arrow function is a function with a single statement in the body
    • works only for anonymous functions
    • they start with the fn keyword
    • the return keyword is not allowed
    • arguments and return types can be type hinted

 
 
 
 


 

// long version
function(arguments)
{ 
  return expression;
}

// short version
fn(arguments) => expression;
1
2
3
4
5
6
7
8

# Type hinting

  • PHP, like many other programming languages, supports (optional) type hinting to specify the expected data type of an argument and return value in a function/class declaration
    • PHP will check whether or not the arguments are of the specified type
    • If not, the run-time will raise an error and execution will be halted

REMARK

# Include

  • Often, you want to use your self-written functions in different PHP files
    • Move the function definitions to a separate file (e.g. course/my_functions.php)
    • Include the content of this file (with the function definitions) in the file course/user_defined_functions.php with the statement include_once 'my_functions.php'

REMARKS

  • It's a good practice to use this technique (of including files) to include a navigation menu, a footer, ... on every page of your application
    • In our project, shared meta-data (shared/meta.php), a navigation bar (shared/nav.php) and a footer (shared/footer.php) are included on every page
  • Notice that we use relative paths in our include_once statements (e.g. include_once('../shared/meta.php')).
    You might want to try include_once('/shared/meta.php'), but this doesn't work as in PHP the starting forward slash / does not correspond to the root of your project, but to the root of your filesystem on the server.
    Use include_once($_SERVER['DOCUMENT_ROOT'] . '/shared/meta.php') to build up paths from the root of your project.
    Read more on https://phpdelusions.net/articles/paths (opens new window).
Last Updated: 8/27/2022, 7:42:58 PM