Functions in PHP

Functions in PHP

In PHP, functions are used to produce some output. Functions in PHP operate a lot like Methods do in Java. Functions can take parameters or arguments and then run code using that input. In a function that takes a parameter, you can set a default value that will be used in the case where no input is received. A "return" statement is used for methods that need to return a value to be used for something else like in another function for example.

Code Example:

<?php
//basic example of a function. Just prints "Hello  World" when called
function sayHello(){
 echo "Hello World";
}
sayHello();
echo '<br />';
//function that uses a loop and condition to print some out put.
function printNumList(){
 for($i=0; $i<=100; $i++){
  if($i%2==0){
   echo $i;
  }
 }
}
printNumList();
echo '<br />';

//function that takes an argument and returns a result.
function addFive($inputNum){
 while($inputNum<=50){
  $inputNum+=5;
 }
 return $inputNum;
}
echo addFive(15);
echo '<br />';

?>


Expected Output:

Hello World
02468101214161820222426283032343638404244464850525456586062646668707274767880828486889092949698100
55

The above is what you should see if you run the program in the browser.

Comments

Popular posts from this blog