PHP Functions
PHP Built-in Functions
- ★ PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a
specific task.
- ★ Please check out our PHP reference for a complete overview of the PHP
built-in functions.
PHP User Defined Functions
Besides the built-in PHP functions, it is possible to create your own 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.
- ★ Syntax:
function functionName() {
code to be executed;
}
★ Example:
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
PHP Function Arguments
- ★
The following example has a function with one argument ($fname). When the familyName() function is called, we
also
pass along a name (e.g. Jani), and the name is used inside the function:
<?php
function familyName($fname) {
echo "$fname Johnson.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
★
The following example has a function with three arguments ($fname, $lname, and $year):
<?php
function fullName($fname, $lname, $year) {
echo "$fname $lname born in $year <br>";
}
fullName("Hege", "Mark", "1975");
fullName("Stale", "Love", "1978");
fullName("Kai Jim", "Walisa", "1983");
?>
★ You can also return values from the function instead of echoing:
function fullName($fname, $lname, $year) {
return "$fname $lname born in $year";
}
echo fullName("Hege", "Michael", 1975) . "<br>";
PHP Default Argument Value
The following example shows how to use a default parameter. If we call the function setHeight() without arguments it
takes the default value as argument:
<?php
function setHeight(int $minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
With int (typed parameter)
setHeight(75.5); // ✅ Becomes 75
setHeight("100"); // ✅ Converts to 100
setHeight("tall"); // ❌ Error in strict mode
If you want to add more parameters with defaults, just make sure required ones come first:
function setBoxSize($width, $height = 100, $depth = 50) {
echo "Box: $width x $height x $depth <br>";
}
setBoxSize(200);
setBoxSize(200,150);
setBoxSize(200,150,20);
PHP Functions - Returning values
To let a function return a value, use the return statement:
<?php
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>
Quadratic Formula Example:
function solveQuadratic($a, $b, $c) {
$discriminant = ($b * $b) - (4 * $a * $c);
if ($discriminant < 0) {
return "No real solutions.";
} elseif ($discriminant == 0) {
$x = -$b / (2 * $a);
return "One real solution: x = $x";
} else {
$sqrtDisc = sqrt($discriminant);
$x1 = (-$b + $sqrtDisc) / (2 * $a);
$x2 = (-$b - $sqrtDisc) / (2 * $a);
return "Two real solutions: x₁ = $x1 and x₂ = $x2";
}
}
// Example usage:
echo "Equation: x² + 5x + 6 = 0<br>";
echo solveQuadratic(1, 5, 6) . "<br><br>";
echo "Equation: x² + 4x + 4 = 0<br>";
echo solveQuadratic(1, 4, 4) . "<br><br>";
echo "Equation: x² + 2x + 5 = 0<br>";
echo solveQuadratic(1, 2, 5);
Passing Arguments by Reference
- In PHP, arguments are usually passed by value, which means that a copy of the value is used in the function and the variable that was passed into the function cannot be changed.
- When a function argument is passed by reference, changes to the argument also change the variable that was passed in. To turn a function argument into a reference, the & operator is used:
<?php
function add_five(&$value) {
$value += 5;
}
$num = 2;
add_five($num);
echo $num;
?>
PHP Arrays
Create an Array in PHP
- ★ In PHP, older syntax
array()
function is used to create an array:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
★ Short array syntax [...], introduced in PHP 5.4
$cars = ["Volvo", "BMW", "Toyota"];
★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
The count() Function
- ★ The
count()
function is used to return the length (the number of elements) of an array:
<?php
$cars = ["Volvo", "BMW", "Toyota"];
echo count($cars);
?>
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:
<?php
$cars = ["Volvo", "BMW", "Toyota"];
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
PHP Associative Arrays
An associative array in PHP lets you use named keys (strings) instead of just numbers to access values.
- ★ Associative arrays are arrays that use named keys that you assign to them.
<?php
$age = [
"Peter"=>"35",
"Ben"=>"37",
"Joe"=>"43"];
echo "Peter is " . $age['Peter'] . " years old.";
?>
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:
<?php
$age = [
"Peter"=>"35",
"Ben"=>"37",
"Joe"=>"43"];
foreach($age as $key => $value) {
echo "Key=" . $key . ", Value=" . $value;
echo "<br>";
}
?>
PHP Contact List Webpage using Associative Arrays
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact List</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
background: #f8f8f8;
}
h1 {
color: #333;
}
table {
border-collapse: collapse;
width: 80%;
background-color: #fff;
}
th, td {
border: 1px solid #ccc;
padding: 10px;
text-align: left;
}
th {
background-color: #eee;
}
</style>
</head>
<body>
<h1>📇 Contact List</h1>
<?php
// Our associative array of contacts
$contacts = [
"alice" => [
"name" => "Alice Smith",
"email" => "alice@example.com",
"city" => "Nashville"
],
"bob" => [
"name" => "Bob Johnson",
"email" => "bob@example.com",
"city" => "Memphis"
],
"carol" => [
"name" => "Carol White",
"email" => "carol@example.com",
"city" => "Knoxville"
]
];
?>
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>City</th>
</tr>
<?php foreach ($contacts as $id => $person) { ?>
<tr>
<td><?php echo $person["name"]; ?></td>
<td><?php echo $person["email"]; ?></td>
<td><?php echo $person["city"]; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
Reference