Appearance
Functions
Built-in functions
- PHP contains lots of built-in functions
- We restrict ourselves to some useful array, string and date functions
Array functions
- Complete list of array functions
- Open course/array_functions.php
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 |
php
<article>
<h2>in_array()</h2>
<?php
$students = ['Doe, John' => 'r0662335', 'Doe, Jane' => 'r0715283', 'Smith, Jeff' => 'r0622915'];
$search = 'r06229152';
$found = in_array($search, $students) ? ' found ' : ' not found ';
echo "<p> Student with r-number $search was <b>$found</b>. </p>\n";
?>
</article>
<article>
<h2>in_array()</h2>
<?php
$students = ['Doe, John' => 'r0662335', 'Doe, Jane' => 'r0715283', 'Smith, Jeff' => 'r0622915'];
$search = 'r06229152';
$found = in_array($search, $students) ? ' found ' : ' not found ';
echo "<p> Student with r-number $search was <b>$found</b>. </p>\n";
?>
</article>
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
String functions
- Complete list of string functions
- Open course/string_functions.php
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 |
php
<article>
<?php
$testString = 'this is a random string to illustrate PHP string functions';
echo "<p> Length of \$testString = " . strlen($testString) . "</p>\n";
echo "<p> Position (first occurrence!) of 'is' in \$testString = " . strpos($testString, 'is') . "</p>\n";
$testString = ucfirst($testString);
echo "<p> \$testString = <code>$testString</code></p>\n";
$subString = substr($testString, strpos($testString, 'P'), 3);
echo "<p> \$subString = <code>$subString</code></p>\n";
$testString = str_replace('PHP', 'some', $testString);
echo "<p> \$testString = <code>$testString</code></p>\n";
$testString = strtoupper($testString);
echo "<p> \$testString = <code>$testString</code></p>\n";
$testString = strtolower($testString);
echo "<p> \$testString = <code>$testString</code></p>\n";
$testString = ucwords($testString);
echo "<p> \$testString = <code>$testString</code></p>\n";
$words = explode(' ', $testString);
echo "<p> \$words = </p>\n";
var_dump($words);
?>
</article>
<article>
<?php
$testString = 'this is a random string to illustrate PHP string functions';
echo "<p> Length of \$testString = " . strlen($testString) . "</p>\n";
echo "<p> Position (first occurrence!) of 'is' in \$testString = " . strpos($testString, 'is') . "</p>\n";
$testString = ucfirst($testString);
echo "<p> \$testString = <code>$testString</code></p>\n";
$subString = substr($testString, strpos($testString, 'P'), 3);
echo "<p> \$subString = <code>$subString</code></p>\n";
$testString = str_replace('PHP', 'some', $testString);
echo "<p> \$testString = <code>$testString</code></p>\n";
$testString = strtoupper($testString);
echo "<p> \$testString = <code>$testString</code></p>\n";
$testString = strtolower($testString);
echo "<p> \$testString = <code>$testString</code></p>\n";
$testString = ucwords($testString);
echo "<p> \$testString = <code>$testString</code></p>\n";
$words = explode(' ', $testString);
echo "<p> \$words = </p>\n";
var_dump($words);
?>
</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
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
Date/time functions
- Complete list of date/time functions
- Open course/date_functions.php
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 |
php
<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>
<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
2
3
4
5
6
7
8
9
10
11
12
- 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
<?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>
<?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
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
Functions without parameters
- A user-defined function (e.g.
function writeMessage(): void
) starts with the keywordfunction
, 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
- 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
- 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 insubtractReduction30(float &$price): void
- In order to do so, precede the parameter in the function definition with
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
php
// long version
function(arguments)
{
return expression;
}
// short version
fn(arguments) => expression;
// long version
function(arguments)
{
return expression;
}
// short version
fn(arguments) => expression;
1
2
3
4
5
6
7
8
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
php
<article>
<h2>Function with type hinting</h2>
<?php
function sum1(int $a, int $b): int
{
return $a + $b;
}
echo "<p>" . sum1(2, 3) . "</p>";
echo "<p>" . sum1(2, 3.1) . "</p>";
echo "<p>" . sum1(2, '3') . "</p>";
?>
</article>
<article>
<h2>Function with type hinting</h2>
<?php
function sum1(int $a, int $b): int
{
return $a + $b;
}
echo "<p>" . sum1(2, 3) . "</p>";
echo "<p>" . sum1(2, 3.1) . "</p>";
echo "<p>" . sum1(2, '3') . "</p>";
?>
</article>
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
REMARK
- Before PHP 8, union types could only be specified in phpdoc annotation comments.
- Now this can be made directly as type hint by specifying the allowed value types in a list separated by the pipe symbol '|'.
- Nullable types, which allow variables or return values to be either of a specific type or
null
, can be indicated using the?
prefix before the type name. For example,?int
represents an integer ornull
. - List of type hint in PHP function parameters and return values
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 tryinclude_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.
Useinclude_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.