Science Library - free educational site

Functions (PHP)

Functions are a technique for making a script easier to manage, and to save memory space. Actions that are executed more than once within a programme can be efficiently defined and executed by a function, whose name is sugestive of its purpose.

Built-in functions (e.g. isset, echo, order, sort, include) cover to a large degree the needs of a PHP script. However, custom functions can be defined simply to aid the effectiveness of a programme. They are defined by the following syntax:

function newFunction() {

// code which defines the actions to be carried out when the newFunction() function is called somewhere in the script

}

Function names may include any combination of alphanumeric characters, but the first character must be a letter or the underscore (_).

Custom functions cannot have the same name as built-in functions. Function names are case insensitive, so newFunction() is the same function as newfunction(), and Newfunction(). However, new_Function() will not call it.

Functions must be defined before they are called, or an undefined function error will result. It is therefore logical to define functions near the top of a page of script.

Arguments

Both built-in and custom functions can take arguments (parameters). An argument is information defined by a constant or a variable, which is imported into a function from the script that calls the function.

function add($first, $second) {

$total = $first+$second;

echo 'Your two numbers total =' .$total;

}

To call the function with the arguments predefined, the following code appears somewhere in the script:

add(10, 2);

Arguments may also have a preset default value:

function add($first, $second = 5) {

$total = $first+$second;

echo 'Your two numbers total =' .$total;

}

The default argument is now optional when calling the function. If the value is not passed to the function, it will use the default.

Returning Values

A function can return a value:

function message($greeting, $name) {

$message = $greeting+$name;

return $message;

}

echo "Message reads: ". message('Hello', 'Peter');

Scope

The scope of a variable is the 'realm' where it has a value and can be accessed. A superglobal variable is always valid. Variables defined on a page are generally valid for that page, but not on another. To pass a variable to another page, the $_GET method can be used.

Where care must be given is variable scope outside and inside functions. Unless specified with global $variable;, a variable defined outside a function is not accessible from within the function, and a variable assigned a value within a function does not have this value outside the function.

Built-in Functions

String replace str_replace() will replace the first string (X) with the second (Y), in the third element ($oldvar).

Syntax: str_replace(find,replace,string,count)

count returns the number of replacements made.

str_replace("old","new",$where,$how_many));

echo "'New' has replaced 'old' ".$how_many." times in ".$where;

$newvar = str_replace('X', 'Y', $oldvar);

e.g.:

$topic = str_replace('_', ' ', urldecode($_GET['topic']));

In this example, the URL brought to a page by the GET function, has underscores (this is because URL uses %20 in place of spaces, so an underscore is used in the URL title) which need to be replaced by spaces before the $topic variable is used in the page itself.

echo strlen("Hello Arthur!"); // outputs 13

echo str_word_count("Hello Arthur!"); // outputs 2

echo strpos("Hello Arthur!", "Arthur"); // outputs 6

echo str_replace("Zaphod", "Arthur", "Hello Zaphod!"); // outputs Hello Arthur!

strtolower(THIS_GOES_TO_LOWER_CASE) //converts string to all lowercase characters

strtoupper(this_goes_to_upper_case) //converts string to all uppercase characters

wordwrap($str) //breaks a string to lines of 32 characters

lcfirst($str) //converts first letter of string to lowercase

ucfirst($str) //converts first letter of string to uppercase

lcwords($str) //converts first letter of all words in string to lowercase

ucwords($str) //converts first letter of all words in string to uppercase

Removing unwanted characters from a string

mysqli_real_escape_string(connection,escapestring);

The mysqli_real_escape_string PHP function escapes special characters in the escapestring so that the modified escapestring may by used in an SQL statement. The escaped characters are: NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.

Content © Renewable-Media.com. All rights reserved. Created : August 28, 2014 Last updated :January 12, 2016

Latest Item on Science Library:

The most recent article is:

Trigonometry

View this item in the topic:

Vectors and Trigonometry

and many more articles in the subject:

Subject of the Week

Resources

Science resources on ScienceLibrary.info. Games, puzzles, enigmas, internet resources, science fiction and fact, the weird and the wonderful things about the natural world. Have fun while learning Science with ScienceLibrary.info.

Science

Great Scientists

Charles-Augustin Coulomb

1736 - 1806

Charles-Augustin de Coulomb, 1736 - 1806, French physicist, whose name is the unit for electrical charge.

Charles-Augustin de Coulomb, 1736 - 1806, French physicist
IT Forum by Sean Bone

Quote of the day...

The optimist proclaims that we live in the best of all possible worlds; and the pessimist fears this is true.