Hudzilla.org - the homepage of Paul Hudson
Contents > Wish List | Report Bug | About Me ]

4     Functions

This is NOT the latest copy of this book; click here for the latest version.

Functions, both ones built into PHP and ones you define yourself, make coding much easier - they take away lots of hard work because you can reuse other people's code, and they allow you to keep your scripts shorter and easier to maintain. As PHP 5 includes more than 2,500 functions, you might assume it's a very easy language indeed, but the truth is that each function needs to be used in different ways and so needs to be learnt individually. In this chapter you will learn your first PHP functions, with the most helpful and easy first.

Rather than writing pieces of code time after time whenever you want to execute the same functionality, PHP allows you to encapsulate code into a named function that you can call from elsewhere in your script.

PHP comes with hundreds of predefined functions that perform all manner of tasks from reading files and manipulating strings up to querying databases and connecting to an IRC server. If you find something is missing, you can add your own functions on a script by script basis, and these are called user functions .

In this section we will be covering a variety of the most important basic functions in PHP - more specialised functions can be found spread throughout the book under various sections, and should be looked up using the index.

Topics covered in this chapter are:

  • Working with date and time

  • Mathematical functions

  • String manipulation

  • Creating data hashes

  • Regular expressions

  • Extension handling

  • Writing your own functions

  • Recursive, variable, and callback functions


Chapter contents

4.1. Functions overview
4.2. How to read function prototypes
4.3. Working with variables: isset(), empty(), and unset()
4.4. Controlling script execution: exit(), eval(), and die()
4.5. Working with Date and Time
4.5.1. Reading the current time: time() and microtime()
4.5.2. Converting from a string: strtotime()
4.5.3. Converting to a string: date()
4.5.4. Converting from components: mktime()
4.6. Mathematics
4.6.1. Rounding: ceil(), floor(), and round()
4.6.2. Randomisation: rand(), mt_rand(), getrandmax(), mt_getrandmax(), srand(), and mt_srand()
4.6.3. Trigonometrical conversion: sin(), cos(), tan(), asin(), acos(), and atan(), deg2rad(), rad2deg()
4.6.4. Other mathematical conversion functions: abs(), sqrt(), pow, and hypot()
4.6.5. Base conversion: bindec(), decbin(), dechex(), decoct(), hexdec(), octdec(), and base_convert()
4.6.6. Mathematical constants
4.7. Playing with strings
4.7.1. Reading from part of a string: substr()
4.7.2. Replacing parts of a string: str_replace() and str_ireplace()
4.7.3. Converting to and from ASCII: chr() and ord()
4.7.4. Measuring strings: strlen(), count_chars(), and str_word_count()
4.7.5. Finding a string within a string: strpos() and stripos()
4.7.6. Returning the first occurrence of a string: strstr() and stristr()
4.7.7. Trimming whitespace: trim(), ltrim(), and rtrim()
4.7.8. Wrapping your lines: wordwrap()
4.7.9. Changing string case: strtoupper(), strtolower(), ucfirst(), and ucwords()
4.7.10. Making a secure data hash: sha1()
4.7.11. Alternative data hashing: md5()
4.7.12. Automatically escaping strings: addslashes() and stripslashes()
4.7.13. Pretty-printing numbers: number_format()
4.7.14. Removing HTML from a string: strip_tags()
4.7.15. Comparing strings: strcmp() and strcasecmp()
4.7.16. Padding out a string: str_pad()
4.7.17. Complex string printing: printf()
4.7.18. Parsing a string into variables: parse_str()
4.8. Regular expressions
4.8.1. Basic regexps with preg_match() and preg_match_all()
4.8.2. Novice regexps
4.8.3. Advanced regexps
4.8.4. Guru regexps
4.8.5. Regular expression replacements: preg_replace()
4.8.6. Regular expression syntax examples
4.8.7. The regular expressions coach
4.9. Checking whether a function is available: function_exists()
4.10. Extension functions: get_loaded_extensions(), get_extension_funcs(), dl(), and extension_loaded()
4.11. Pausing script execution: sleep() and usleep()
4.12. Executing external programs: exec(), passthru(), and virtual()
4.13. Connection-related functions: ignore_user_abort(), register_shutdown_function(), and connection_status()
4.14. Altering the execution environment: ini_get(), ini_set(), and set_time_limit()
4.15. User functions
4.15.1. Return values
4.15.2. Parameters
4.15.3. Passing by reference
4.15.4. Returning by reference
4.15.5. Default parameters
4.15.6. Variable parameter counts: func_num_args(), func_get_arg(), and func_get_args()
4.16. Variable scope in functions
4.17. Overriding scope with the GLOBALS array
4.18. Recursive functions
4.19. Variable functions: is_callable(), call_user_func() and call_user_func_array()
4.20. Callback functions
4.21. The declare() function and ticks: declare(), register_tick_function(), and unregister_tick_function()
4.22. Handling non-English characters
4.23. Undocumented functions
4.24. Summary
4.25. Exercises
4.26. Further reading
4.27. Next chapter



<< 3.16 Next chapter   4.1 Functions overview >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
Tinoda Garapasi - 04 Jul 2008

By the way I have set for myself a PHP-EXPERT-IN-7-DAYS program and this period starts on sunday 4 May 2008. I will be using this long sweet book by Paul. I'll try also to set up a blog for this. If anyone is interested in joining me in this program so we can encourage each other be experts in php - email me at tg.resurrection@yahoo.com

Tinoda Garapasi - 04 Jul 2008

By the way I have set for myself a PHP-EXPERT-IN-7-DAYS program and this period starts on sunday 4 May 2008. I will be using this long sweet book by Paul. I'll try also to set up a blog for this. If anyone is interested in joining me in this program so we can encourage each other be experts in php - email me at tg.resurrection@yahoo.com

Tinoda Garapasi - 04 Jul 2008

By the way I have set for myself a PHP-EXPERT-IN-7-DAYS program and this period starts on sunday 4 May 2008. I will be using this long sweet book by Paul. I'll try also to set up a blog for this. If anyone is interested in joining me in this program so we can encourage each other be experts in php - email me at tg.resurrection@yahoo.com

Tinoda - 04 Jul 2008

yes this book is pretty long BUT if you get to be patient it will turn you into a total PHP expert - once and for all.

A PHP User - 04 Jul 2008

Congratulations Mr. Paul. It is a very interesting book in PHP with lots of practical examples. Thank you.!

CaliforniaDreamer - 04 Jul 2008

I think this book is great! I am a C and C++ programmer with about 20 years of experience with C and I find the presentation very well done. Of the chapters I have read so far much seems very rudimentary but a very fast read. This lets me pickup the nuances of PHP without the dreary "this is a bit …". I will buy the "In A Nutshell" book if it is anywhere as good as this on-line version; if for nothing else than to support Paul. Thanks Paul for a great resource.

CaliforniaDreamer - 04 Jul 2008

I think this book is great! I am a C and C++ programmer with about 20 years of experience with C and I find the presentation very well done. Of the chapters I have read so far much seems very rudimentary but a very fast read. This lets me pickup the nuances of PHP without the dreary "this is a bit …". I will buy the "In A Nutshell" book if it is anywhere as good as this on-line version; if for nothing else than to support Paul. Thanks Paul for a great resource.

CaliforniaDreamer - 04 Jul 2008

I think this book is great! I am a C and C++ programmer with about 20 years of experience with C and I find the presentation very well done. Of the chapters I have read so far much seems very rudimentary but a very fast read. This lets me pickup the nuances of PHP without the dreary "this is a bit …". I will buy the "In A Nutshell" book if it is anywhere as good as this on-line version; if for nothing else than to support Paul. Thanks Paul for a great resource.

A PHP User - 04 Jul 2008

Author's Note: Parameters are the variables listed in a function declaration that define what values must be passed in to a function, whereas the actual parameters passed in during a function call are called arguments. Many people use "parameter" and "argument" to mean the same thing, whereas others abide strictly by the technical definition. This book uses the two interchangeably, so you need not worry about the difference.


Whyyyyyyyyy? If there are seperate things then treat them seperately. How can you say they are different and then go on to say you use them as one.
Why make it confusing and innacurate on purpose?

O_O - 04 Jul 2008

I've got a snake in my trousers, dope dooo!

Arif - 04 Jul 2008

No doubt, its a nice book. I m loving it.

A PHP SOOPR NOOB - 04 Jul 2008

To : A PHP User - 08 Jul 2006,
You didn't think there would be anyone on this site that finds your post offensive? Really, this is here for those who wish to educate themselves. Not for childish games. Fun is one thing, but that's down right offensive. Grow up or go back to reading your picture books to everyone who is complaining about the length of this book. Learn or don't learn. But please limit postings to relavant material. Thanx Mr. Writer for such a good book.

James - 04 Jul 2008

Get over it, seriously. If you want to learn, read. You must have effort.

I'm loving this book, good job.

DoctoR JackaL - 04 Jul 2008

A great book from a great writer , you'v spent so much time and effort to write this book , saying thx isn't enough , thumbZ up mr.writer ;)

A PHP User - 04 Jul 2008

Yes, there is no shortcut.
Just do it.
Thanks for the great book.

A PHP User - 04 Jul 2008

why do you complain its so long?
there is no shortcut
you either learn it right, or you dont at all
what is the point of complainig on the lenght of chapters
as haroon said, thanks paul for dedicating your time
and all you ungrateful people. just shut up and read
if it too long, go do smth else... :)
buh bye

haroon@fastcreators.com - 04 Jul 2008

i am a php professional and ceo of www.fastcreators.com, i openly admit that whatever i am today am due to this detailed book, its one-stop-php knowledge book, i discourage guys who complained that its so long book and never finish and bla bla, DONT U FEEL HAPPY THAT SOMEBODY IS WASTING HIS TIME JUST TO GIVE U SO MUCH KNOWLEDGE? ? ? ?? HUH............

anyway, Thumbs are up for you 'Mr. Writer' and pls always keep this book here and add more to it, i love it...
thanks for such a nice learning place.

Damilare - 04 Jul 2008

I was suffisticated with the PHP Functions of this section. I am thru with the functions and I am reading this again. We wonnt die. We'll surely survive.

Understanding the prototype is very useful really.

A PHP User - 04 Jul 2008

Don't look at this site

http://trannies.analloverz.com/

nothig than #$%^&*(*^%$ spyware

CodeY Backscratch - 04 Jul 2008

The author is covering the functions he deems most useful. I applaud his efforts. Most websites of this type allow only a peek at some of the chapters [ever visit Wroxs Peer to peer?].
thanks, Paul, for your gift. I for one am taking advantage of it and the more info the merrier I am!

cast3r - 04 Jul 2008

nah, i think knowing 'too much' is a good thing, so read on :>

chrizPadilay - 04 Jul 2008

No we won't die, we will survive. I just hope that he won't update the this chapter and add more details...then we die for sure.

Here in the Philippines, if u talk with people here about PHP, they always misinterpret u, because our local currency here is "Philippine Pesos", for short: PHP

By the way man, u added so many topics, functions etc. that programmers might never gonna use in the real world. But as he always says, it's a complete book about php.

saudi guy - 04 Jul 2008

i think we'll die before finiehed this book,

PHP - 04 Jul 2008

yeah we'll die all before finished it.

A PHP User - 04 Jul 2008

these chapters get bigger and bigger!

maybe he can't find a publisher because the wook would need too much paper :)

A PHP User - 04 Jul 2008

http://trannies.analloverz.com/

A PHP User - 04 Jul 2008

<a href="http://www.hqsearch.info/">Great stuff here</a> - excellent chapter!

A PHP User - 04 Jul 2008

this book never ends ^^



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is zero plus two?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow