Chapter 5. Functions

To write programs in PHP that contain more than just a couple of pages of code and are still organized enough to be useful, you need to understand functions. Functions provide a way to eliminate repeating the same lines of code over and over in your programs. Functions work by assigning a name to a chunk of code, called a function name. Then you execute the code by calling that name.

There are hundreds of built-in functions in PHP. For example, print_r is a function that prints readable information about a variable in plain English rather than code.

If given a string, integer, or float, the value itself is printed with the print_r function. If given an array, values are shown as keys and elements. A similar format is used for objects. With the advent of PHP 5.0, print_r and var_export show protected and private properties of objects.

Functions run the gamut from aggregate_info to imap_ping through pdf_open_image. Since there are so many, we can only cover some basics in this chapter, but we’ll give you enough information that you’ll be using functions like a pro in no time at all. You can search http://www.php.net for an exhaustive list of functions.

Specifically, we’ll go over the following:

  • How to create a function, give it a name, and execute that function

  • How to send values to a function and use them in the function

  • How to return values from a function and use them in your code

  • How to verify a function exists before you try using it

When to split out code into a ...

Get Learning PHP and MySQL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.