Core PHP

General Functions

A function encapsulates a block of code so that that block of code may be used repeatly. Functions may take in values and return them. They may even call themselves. Here, we have an example of each type of functions.

Functions.php

<?php
  // 1. A simple function with no parameters or return value:
  function CountToTen() {
    for ($i = 1; $i <= 10; ++$i) {
      echo $i."  ";
    }
    echo "<br /><br />";
  }

  // 2. A function that takes an argument tha is passed in by value:
  function PrintParameter($sParam) {
    echo $sParam."<br /><br />";
  }

  // 3. A function with an argument that is passed in by reference:
  function AddOneToReference(&$irN) {
    ++$irN;
  }

  // 4. A function with default arguments (these must be set on the last parameters):
  function PrintWithDefault($sNoDefault, $sWithDefault = "XoaX.net") {
    echo "No Default = ".$sNoDefault."<br />";
    echo "With Default = ".$sWithDefault."<br /><br />";
  }

  // 5. A function that takes an array argument:
  function PrintArray($saArray) {
    $iSize = count($saArray);
    for ($i = 0; $i < $iSize - 1; ++$i) {
      echo $saArray[$i].",  ";
    }
    if ($iSize >= 1) {
      echo $saArray[$iSize - 1]."<br /><br />";
    }
  }

  // 6. A function with variable arguments (automatically turned into an array):
  function PrintAll(...$saValues) {
    foreach ($saValues as $sString) {
      echo $sString." ";
    }
    echo "<br /><br />";
  }

  // 7. A function with a return value:
  function Sum($A1, $A2) {
    return ($A1 + $A2);
  }


  // 1.
  echo "1. A Simple function with no parameters or return value:<br />";
  CountToTen();

  // 2.
  echo "2. A Function that takes an argument tha is passed in by value:<br />";
  PrintParameter("XoaX.net");

  // 3.
  echo "3. A function with an argument that is passed in by reference:<br />";
  $i = 5;
  echo "Before = ".$i."<br />";
  AddOneToReference($i);
  echo "After = ".$i."<br /><br />";

  // 4.
  echo "4. A function with default arguments (these must be set on the last parameters):<br />";
  PrintWithDefault("XoaX");

  // 5.
  echo "5. A function that takes an array argument:<br />";
  $saTrinity = array("Father", "Son", "Holy Spirit");
  PrintArray($saTrinity);

  // 6.
  echo "6. A function with variable arguments (automatically turned into an array):<br />";
  PrintAll("Peter", "Paul", "James", "John");

  // 7.
  echo "7. A function with a return value:<br />";
  echo "Sum of 3 + 4 = ".Sum(3, 4)."<br />";
  // Passing arguments as an array
  echo "Sum of 6 + 9 with array = ".Sum(...[6, 9])."<br /><br />";
?>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.