Using a custom function method to implement the 99 multiplication table, a function is a block of code that can be executed whenever it is needed.
To create a PHP function:
All functions start with the keyword "function ()".
Named function – the name of the function should indicate its function. The function name begins with a letter or an underscore.
Add "{" – the part that follows the curly braces of the opening is the code for the function.
Insert Function code
Add a "}" – The function ends by closing the curly braces.
Example
A simple function that outputs my name when it is invoked:
| The code is as follows |
Copy Code |
<body>
<?php
function Writemyname ()
{
echo "David Yang";
}
Writemyname ();
?>
</body>
|
Using PHP functions
Now we're going to use this function in the PHP script:
| The code is as follows |
Copy Code |
|
<body>
<?php
function Writemyname ()
{
echo "David Yang";
}
echo "Hello world!<br/>";
echo "My name is";
Writemyname ();
echo ". <br/>that ' s right,";
Writemyname ();
echo "is my name.";
?>
</body>
The output of the above code:
Hello world!
My name is David Yang.
That's right, the David Yang was my name |
Let's write a function to implement the 99 multiplication table
| The code is as follows |
Copy Code |
<php?
/**
* 9*9 Multiplication table
* String fun_99 (int $start =1, int $end =1,bool $sort =true)
* $start starting number must be between 1-9 and must be an integer
* $end End value must be between 1-9 and must be an integer and greater than $start
* $sort for sorting, true for positive order, false for reverse
*/
echo "
function fun_99 ($start =1, $end =9, $sort =true) {
if ($start <1| | $start >9) {
Return ' starting number must be between 1-9 ';
}
if ($end <1| | $end >9) {
Return ' end value must be between 1-9 ';
}
if ($start!= (int) ($start)) {
Return ' Starting number must be an integer ';
}
if ($end!= (int) ($end)) {
Return ' end value must be an integer ';
}
if ($start > $end) {
Return ' starting number must be less than the end value ';
}
$str = ';
if ($sort) {
for ($i = $start; $i <= $end; $i + +)
{
$str = $str. " <br> ";
for ($n = $start; $n <= $end; $n + +)
{
if ($i >= $n)
{
$str = $str. " $i * $n ". = '. $i * $n. " &NBSP ";
}
}
}
}else{
for ($i = $end; $i >= $start; $i-)
{
$str = $str. " <br> ";
for ($n = $end; $n >= $start; $n-)
{
if ($i >= $n)
{
$str = $str. " $i * $n ". = '. $i * $n. " &NBSP ";
}
}
}
}
return $str;
}
echo fun_99 (1,9,true);
?>
|
Get the same result as HTML