PHP Custom functions are created through the function keyword, which can improve code modularity and reusability: Creation method: Use the function keyword, function name and parameters to create a function. Calling method: Enter the function name and pass parameters to call the function. Practical case: Use a custom function to count the number of prime numbers in a specified range, such as countPrimes(1, 100) to return the number of prime numbers in the range (25).
PHP Functions Custom functions: Create flexible and scalable code
Custom functions are a method created in PHP Powerful way to customize logic blocks. They make code more modular, reusable, and easier to maintain.
Create a custom function
To create a custom function, use the function
keyword, followed by the function name and parameters.
function sum($a, $b) { return $a + $b; }
Call a custom function
To call a custom function, just enter the function name and pass the necessary parameters.
$result = sum(5, 10); // Ergebnis 15
Practical case: Calculating the number of prime numbers
Suppose you need a function that calculates the number of prime numbers in a given range. You can easily implement this using a custom function:
function countPrimes($start, $end) { $count = 0; for ($i = $start; $i <= $end; $i++) { if (isPrime($i)) { $count++; } } return $count; } function isPrime($number) { if ($number <= 1) { return false; } for ($i = 2; $i <= sqrt($number); $i++) { if ($number % $i == 0) { return false; } } return true; }
Using a custom function
Now you can use the countPrimes()
function to count the number of prime numbers in any range:
$primeCount = countPrimes(1, 100); // Ergebnis 25
The above is the detailed content of PHP Functions Custom Functions: Create flexible and scalable code. For more information, please follow other related articles on the PHP Chinese website!