Home > Article > Backend Development > Introduction to nine more practical PHP functions_PHP tutorial
Even after using PHP for many years, you will stumble upon some functions and functions that you never knew about. Some of them are very useful but underutilized. Not everyone will read the manual and function reference page after page from cover to cover!
1. Functions with any number of parameters
You may already know that PHP allows defining functions with optional parameters. But there are also methods that completely allow any number of function parameters. The following is an example of optional parameters:
The following is the quoted content:
// function with 2 optional arguments
function foo($arg1 = , $arg2 = ) {
echo "arg1: $ arg1
";
echo "arg2: $arg2
";
}
foo(hello,world);
/* prints:
arg1: hello
arg2: world
*/
foo();
/* prints:
arg1:
arg2:
*/
Now let’s see how to create a function that accepts any number of arguments. This time we need to use the func_get_args() function:
The following is the quoted content:
// yes, the argument list can be empty
function foo() {
;
foreach ($args as $k => $v) {
echo "arg".($k 1).": $v
";
}
}
foo();
/* prints nothing */
foo(hello);
/* prints
arg1: hello
*/
foo(hello, world, again);
/* prints
arg1: hello
arg2: world
arg3: again
*/
2. Use Glob() to find files
Many PHP functions have long descriptive names. However, it may be difficult to tell what the glob() function can do unless you have used it many times and are familiar with it. It. Think of it as a more powerful version of the scandir() function, which can search for files according to a certain pattern.
The following is the quoted content:
// get all php files
$files = glob(*.php);
print_r($files);
/* output looks like:
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
)
*/
You You can get multiple files like this:
The following is the quoted content:
// get all php files AND txt files
$files = glob(*.{php,txt}, GLOB_BRACE);
print_r($files);
/* output looks like:
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
[4] => log.txt
[5] => test.txt
)
*/
Please note that these files can actually return a path, depending on the query conditions:
The following is the quoted content:
$files = glob(../images /a*.jpg);
print_r($files);
/* output looks like:
Array
(
[0] => ../images/apple.jpg
[1] => ../images/art.jpg
)
*/
If you want to get the full path of each file, you can call the realpath() function :
The following is the quoted content:
$files = glob(../images/a*.jpg);
// applies the function to each array element
$files = array_map(realpath ,$files);
print_r($files);
/* output looks like:
Array
(
[0] => C:wampwwwimagesapple.jpg
[1 ] => C:wampwwwimagesart.jpg
)
*/