PHP: Functions

This entry is part 29 of 54 in the series PHP Tutorial

Similar to other programming languages, functions are blocks of code that together achieve a more complex task.

Functions are not executed until you call upon them.

/* Defining a PHP Function */
function writeMsg($name)
  echo "Hi, $name\n";  
  echo "How is life?";
/* Calling a PHP Function */
$john = "John";

In this example, we have passed a parameter John into the function writeMsg.

Note also that in PHP, function names are case insensitive.

If the function only returns a value, we can use the return statement.


 function sum($x,$y)
  return $z;

  echo "8 + 10 = " . sum(5,10) . "\n";
  echo "2 + 13 = " . sum(7,13) . "\n";


PHP: Variables

This entry is part 4 of 54 in the series PHP Tutorial

Sit back and relax.

Let’s not hurry and move to the more complex example.  Sometimes, it is good to just run code written by others.

We now look at how variables are declared in PHP.


$myText = "Happy New Year! "; 
$myNum = 2014;

echo $myText;
echo "The year is ". $myNum;
Try The Code

In PHP, a variable is preceded by a $ sign and declaration is actually not needed.

As in the example above, if you have $myNum = 2014, the PHP parser will interprete $myNum as an integer directly.

The $myText is a string variable as the text Happy New Year! is enclosed in a double quote.

Notice in line 8, there is a .(dot) in the line.  The . in PHP is a string concatenation. It joins a string and an integer or a string to a string together.