Home arrow PHP arrow Page 3 - PHP Functions

Setting Default Values - PHP

If you're looking for a way to save time when you program, look no further. Creating functions lets you reuse code that you've used before without having to rewrite the whole thing. Keep reading to learn how.

  1. PHP Functions
  2. Functions that Take Arguments
  3. Setting Default Values
  4. Creating Functions that Return a Value
  5. Using Variables in Functions
By: Jacques Noah
Rating: starstarstarstarstar / 46
August 01, 2006

print this article



When creating a function that takes arguments, you can set default values for it:

function function_name($argument2, $argument = 6){



Why would you want to set default values in a function? Well, if you are for example writing a program that involves calculating tax, which does not change often but does change sometimes, a function like this would be appropriate. It allows the assumption of a value, but still permits you to change the value when needed.

The default value is overwritten when you specify a value, otherwise the value will stay the same. For example, let's create a new function that will take your age, first name and last name:

function mydetails($firstname, $lastname, $age=23){

echo "My name is " .$firstname. " " .$lastname. " and I am
".$age." years old.";


To call this function, type: mydetails(34,'John','Doe')

And the result will be...

My name is John Doe and I am 34 years old

As you can see, the default value of 23 has been overwritten to 34.

If, for example, you call this function without the $age argument, the function will assume that $firstname is the first argument. In other words, it will replace $age with $firstname and $firstname with $lastname. In that case, when you call this function, the results will be:

My name is Doe and I am John years old.

Just make sure that you write the default values after the other standard values (the arguments without defaults):

function mydetails($firstname, $lastname, $age=23){

echo "My name is " .$firstname. " " .$lastname. " and I am
".$age." years old.";


This is because PHP assigns the values directly to the arguments as they are received from the call line.

>>> More PHP Articles          >>> More By Jacques Noah

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: