PHPFront

Home > PHP Tutorials > Functions
The PHP website created by its users!



Functions


Functions can be used to reduce the size and complexity of your PHP code. Your code will be much easier to read and maintain for you, and anyone that reads your code.

Functions are simply chunks of code which are declared once, and can be called throughout the script.

One of the great benefits of functions, is portability. Let's say you create a PHP application using a function to resize images throughout your site. After the developement of the application is done, you realize you've made a mistake in your resizing code. All you would have to do; was edit the code in the resize function, instead of updating every php file which resizes images.

Here is how to declare a function:


<?php

function Name() {

//code here
}
?>


Thats the basic structure for declaring a function.

Here's a more detailed function:


<?php

function make_bold ($string) {

$string = '<strong>' . $string . '<strong>';

return $string;
}
?>


<strong>$string</strong> is the variable we are passing through our '<strong><em>make_bold</em></strong>' function.

<strong>return $string;</strong> passes the <strong>$string</strong> variable back to the original script that called the function. Don't worry if you don't understand at this point, it will become clearer soon.

Here is how you would use the function:


<?php

$string = 'Hello im text';

$bold_string = make_bold($string);

echo $bold_string;

?>


The above code will output "hello im text" in bold type.

There are so many uses for functions in PHP, including BB code parsing, email address verification and user authentication.