Chapter 5. Functions

To write PHP programs that contain more than just a couple pages of code and are still organized enough to be useful, you need to understand functions. Functions let you eliminate repeating the same lines of code over and over in your programs. Functions work by assigning a name called a function name to a chunk of code. 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. In 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 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 that a function exists before you try using it

When to split out code into a function is a bit of a judgment ...

Get Learning PHP & MySQL, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.