Detailed explanation of arbitrary number of parameters and search file examples of PHP function

伊谢尔伦
Release: 2023-03-12 06:00:01
Original
1609 people have browsed it

1. PHP functionsAny number of parameters

You may know that PHP allows you to define a function with default parameters. But you may not know that PHP also allows you to define a function with completely arbitrary parameters
Here is an example showing you a function with default parameters:

// 两个默认参数的函数
function foo($arg1 = '', $arg2 = '') {
echo "arg1: $arg1\n";
echo "arg2: $arg2\n";
}
foo('hello','world');
/* 输出:
arg1: hello
arg2: world
*/
foo();
/* 输出:
arg1:
arg2:
*/
Copy after login

Now let’s take a look at an indefinite parameter function, which uses the func_get_args() method:

// 是的,形参列表为空
function foo() {
// 取得所有的传入参数的数组
$args = func_get_args();
foreach ($args as $k => $v) {
echo "arg".($k+1).": $v\n";
}
}
foo();
/* 什么也不会输出 */
foo('hello');
/* 输出
arg1: hello
*/
foo('hello', 'world', 'again');
/* 输出
arg1: hello
arg2: world
arg3: again
*/
Copy after login

2. Glob() Find files
Many PHP functions have a relatively long self-explanatory function name , however, when you see glob(), you may not know what this function is used for, unless you are already familiar with it.
You can think of this function as ?scandir(), which can be used to find files.

// 取得所有的后缀为PHP的文件
$files = glob('*.php');
print_r($files);
/* 输出:
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
)
*/
Copy after login

You can also search for multiple suffixes

// 取PHP文件和TXT文件
$files = glob('*.{php,txt}', GLOB_BRACE);
print_r($files);
/* 输出:
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
[4] => log.txt
[5] => test.txt
)
*/
Copy after login

You can also add the path:

$files = glob('../images/a*.jpg');
print_r($files);
/* 输出:
Array
(
[0] => ../images/apple.jpg
[1] => ../images/art.jpg
)
*/
Copy after login

If you want to get the absolute path, you can call ?realpath () function:

$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:\wamp\www\images\apple.jpg
[1] => C:\wamp\www\images\art.jpg
)
*/
Copy after login

The above is the detailed content of Detailed explanation of arbitrary number of parameters and search file examples of PHP function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template