Function parameters in PHP

Oct 27, 2009 Author: Developer

A function is used to give a complex task a shorter form by naming it; that is, a group of statements is merged into a function, so that, when the function is executed, all of its statements are executed.

 You have already seen some functions. For example, the string functions strlen(), substr(), andstrpos() are all functions supplied to you by PHP. These tasks could becompleted using a series of loops, but doing so would make a program seemmuch more complex than necessary.

Translating those loops into functionsmakes the code clearer and more organized. Although PHP provides many useful functions, they’re all fairly basic; tokeep your programs organized, you’ll need to create some functions on your own, as well.

The values specified in the functions definition are known as the functions parameters. When the function is called, the values given as parameters are often referred to as the functions arguments.

The following program uses a function that takes three parameters:$strName, $intAge, and $intGender. Calling the function outputs the three parameters in a human-readable sentence.

outputSentence(‘Kathy Williams’, 43, ‘female’);
function outputSentence($strName, $intAge, $strGender)
$strName is a string,
$intAge is an integer greater than 0,
$strGender is a string containing either ‘male’ or ‘female’
Outputs a sentence.
echo “$strName is a $intAge-year old $strGender.”;
The output for this program will be:

Kathy Williams is a 43-year old female.

This function takes three parameters in its parameter list.Notice that the grammar of the output string hasn’t changed (“a”should have changed to “an”). Some programmers and their clientsdon’t mind this sort of problem, but it’s possible to modify this functionto always use correct grammar, thus producing a more professionalresult.

views 4252
  1. Add New Comment