Core PHP

Functions with Variable Arguments

This PHP code is an example program that demonstrates how to write functions with a variable number of arguments in PHP.

FunctionsWithVariableArguments.php

<?php

  // This function can take any number of arguments
  // It returns an equation as a string
  function EquationOfSum(...$qaValues) : string {
    $sEquation = "";
    $iSum = 0;
    $iLastKey = array_key_last($qaValues);
    foreach($qaValues as $iKey => $iValue) {
      $sEquation .= $iValue;
      $iSum += $iValue;
      if ($iKey == $iLastKey) {
        $sEquation .= " = ";
      } else {
        $sEquation .= " + ";
      }
    }
    $sEquation .= $iSum;
    return $sEquation;
  }

  // Call the function several times with different numbers of arguments.
  echo EquationOfSum(2)."<br />";
  echo EquationOfSum(10, 6)."<br />";
  echo EquationOfSum(7, 6, 3, 9)."<br />";

  // Call the function, passing the elements of the array as arguments.
  $iaArray = array(11, 22, 33, 44, 55);
  echo EquationOfSum(...$iaArray)."<br />";

?>
 

Output

 
 

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