Functions A function is a block of code with a name. function functionName() { code to be executed; }
The function will not execute unless it is called. function writeMsg() { echo "Hello world!"; } writeMsg(); // call the function // Hello world! By calling the name of the function, we can use it repeatedly.
Variable Scope A variable outside a function is not available inside a function. A variable inside a function is not available outside the function.
Information can be passed to functions through arguments Information can be passed to functions through arguments. An argument is like a variable. function writeMsg($message) { echo $message; } writeMsg("Take me to your leader"); // Take me to your leader
Functions can accept multiple arguments, separated by a comma Functions can accept multiple arguments, separated by a comma. function nameAge($name, $year) { $age = 2014 - $year; echo "$name is $age years old"; } nameAge("Barack Obama", "1961"); // Barack Obama is 53 years old
Function arguments can be given a default value Function arguments can be given a default value. function setScore($minscore = 25) { echo "The score is $minscore <br />"; } setScore(110); setScore(); // Uses 25 by default setScore(98); setScore(101);
Return What if we need to store a value inside a function and use it later? function squareNum($x) { $square = $x * $x; return $square; }
Assign the function call to a variable function squareNum($x) { $square = $x * $x; return $square; } $output = squareNum(4); echo $output; // 16
A function may only return one value, but that value can be an array (or an object). When a function reaches return, the function terminates and the function is exited.
Echo the function call to immediately access return function centsToDollars($cents) { $total = $cents / 100; return $total; } echo "$" . centsToDollars(1228); // $12.28
Function with array as an argument function passArray($colors) { foreach ($colors as $name) { echo "$name <br />"; } passArray($colors = array("orange", "blue", "green", "red", "purple"));