search
HomeBackend DevelopmentPHP ProblemWhat are the advanced functions of php

What are the advanced functions of php

PHP Advanced Functions

1、call_user_func

// 官网地址:
http://php.net/manual/zh/function.call-user-func.php

2、get_class

// 官网地址:
http://php.net/manual/zh/function.get-class.php

3.get_called_class

// 官网地址:
http://php.net/manual/zh/function.get-called-class.php

4.array_map

// 官网地址:http://php.net/manual/zh/function.array-map.php
//为数组的每个元素应用回调函数
示例:
$str = '1 ,2,3';
$res = array_map(function ($v) {
    return intval(trim($v)) * 2;
}, explode(',', $str));
$res的返回结果:
array(3) { [0]=> int(2) [1]=> int(4) [2]=> int(6) }

5.strpos

 // http://php.net/manual/zh/function.strpos.php
//查找字符串首次出现的位置,从0开始编码,没有找到返回false
示例:
$time = "2019-03-02 12:00:00";
if(strpos($time,':') !== false){
    $time = strtotime($time);
}
echo $time;

6.array_reverse

// 官网地址:http://php.net/manual/zh/function.array-reverse.php
//返回单元顺序相反的数组
示例:
$time = "12:13:14";
$arrTime = array_reverse(explode(':',$time));
var_dump($arrTime);
array(3) { [0]=> string(2) "14" [1]=> string(2) "13" [2]=> string(2) "12" }

7, pow

// 官网地址:http://php.net/manual/zh/function.pow.php
//指数表达式
示例:
$time = "12:13:14";
$arrTime = array_reverse(explode(':',$time));
$i = $s = 0;
foreach($arrTime as $time){
    $s += $time * pow(60,$i);  // 60 的 $i 次方
    $i ++;
}
var_dump($s);
int(43994)

8, property_exist

// 官网地址:http://php.net/manual/zh/function.property-exists.php
// 检查对象或类是否具有该属性
//如果该属性存在则返回 TRUE,如果不存在则返回 FALSE,出错返回 NULL
示例:
class Test
{
    public $name = 'daicr';
    public function index()
    {
        var_dump(property_exists($this,'name')); // true
    }
}

9, passthru

// 官网地址:http://php.net/manual/zh/function.passthru.php
//执行外部程序并且显示原始输出
//功能和exec() system() 有类似之处
示例:
passthru(\Yii::$app->basePath.DIRECTORY_SEPARATOR . 'yii test/index');

10, array_filter

// 官网地址:http://php.net/manual/zh/function.array-filter.php
//用回调函数过滤数组中的单元
示例:
class TestController extends yii\console\Controller
{
    public $modules = '';
    public function actionIndex()
    {
        //当不使用callBack函数时,array_filter会去除空值或者false
        $enableModules = array_filter(explode(',',$this->modules));
        var_dump(empty($enableModules)); //true
        //当使用callBack函数时,就会用callBack过滤数组中的单元
        $arr = [1,2,3,4];
        $res = array_filter($arr,function($v){
           return $v & 1;  //先转换为二进制,在按位进行与运算,得到奇数
        });
        var_dump($res);
        //array(2) { [0]=> int(1) [2]=> int(3) }
    }
}

11. current

// 官网地址:http://php.net/manual/zh/function.current.php
//返回数组中的当前单元
$arr = ['car'=>'BMW','bicycle','airplane'];
$str1 = current($arr); //初始指向插入到数组中的第一个单元。
$str2 = next($arr);    //将数组中的内部指针向前移动一位
$str3 = current($arr); //指针指向它“当前的”单元
$str4 = prev($arr);    //将数组的内部指针倒回一位
$str5 = end($arr);     //将数组的内部指针指向最后一个单元
reset($arr);           //将数组的内部指针指向第一个单元
$str6 = current($arr);
$key1 = key($arr);     //从关联数组中取得键名
echo $str1 . PHP_EOL; //BMW
echo $str2 . PHP_EOL; //bicycle
echo $str3 . PHP_EOL; //bicycle
echo $str4 . PHP_EOL; //BMW
echo $str5 . PHP_EOL; //airplane
echo $str6 . PHP_EOL; //BMW
echo $key1 . PHP_EOL; //car
var_dump($arr);   //原数组不变

12. array_slice

// 官网地址:http://php.net/manual/zh/function.array-slice.php
//从数组中取出一段
示例:
$idSet = [1,2,3,4,5,6,7,8,9,10];
$total = count($idSet);
$offset = 0;
$success = 0;
while ($offset < $total){
    $arrId = array_slice($idSet,$offset,5);
    //yii2的语法,此处,注意array_slice的用法就行
    $success += $db->createCommand()->update($table,[&#39;sync_complate&#39;=>1],[&#39;id&#39;=>$arrId])->execute(); 
    $offset += 50;
}
$this->stdout(&#39;共:&#39; . $total . &#39; 条,成功:&#39; . $success . &#39; 条&#39; . PHP_EOL,Console::FG_GREEN); //yii2的语法

13. mb_strlen()

// 官网地址:http://php.net/manual/zh/function.mb-strlen.php
//获取字符串的长度
//strlen 获取的是英文字节的字符长度,而mb_stren可以按编码获取中文字符的长度
示例:
$str1 = &#39;daishu&#39;;
$str2 = &#39;袋鼠&#39;;
echo strlen($str1) . PHP_EOL;                //6
echo mb_strlen($str1,&#39;utf-8&#39;) . PHP_EOL;  //6
echo strlen($str2) . PHP_EOL;               // 4 一个中文占 2 个字节
echo mb_strlen($str2,&#39;utf-8&#39;) . PHP_EOL;  //2
echo mb_strlen($str2,&#39;gb2312&#39;) . PHP_EOL; //2

14. list

// 官网地址:http://php.net/manual/zh/function.list.php
//把数组中的值赋给一组变量
示例:
list($access,$department)= [&#39;all&#39;,&#39;1,2,3&#39;];
var_dump($access); // all

15, strcasecmp

// 官网地址:https://www.php.net/manual/zh/function.strcasecmp.php
//二进制安全比较字符串(不区分大小写)
//如果 str1 小于 str2 返回 < 0; 如果 str1 大于 str2 返回 > 0;如果两者相等,返回 0。
示例:
$str1 = &#39;chrdai&#39;;
$str2 = &#39;chrdai&#39;;
var_dump(strcasecmp($str1,$str2)); // int 0

16, fopen rb

// 官网地址:https://www.php.net/manual/zh/function.fopen.php
//1、使用 &#39;b&#39; 来强制使用二进制模式,这样就不会转换数据,规避了widown和unix换行符不通导致的问题,
//2、还有就是在操作二进制文件时如果没有指定&#39;b&#39;标记,可能会碰到一些奇怪的问题,包括坏掉的图片文件以及关于\r\n 字符的奇怪问题。
示例:
$handle = fopen($filePath, &#39;rb&#39;);

17, fseek

// 官网地址:https://www.php.net/manual/zh/function.fseek.php
//在文件指针中定位
//必须是在一个已经打开的文件流里面,指针位置为:第三个参数 + 第二个参数
示例:
//将文件指针移动到文件末尾 SEEK_END + 0
fseek($handle, 0, SEEK_END);

18, ftell

// 官网地址:https://www.php.net/manual/zh/function.ftell.php
//返回文件指针读/写的位置
//如果将文件的指针用fseek移动到文件末尾,在用ftell读取指针位置,则指针位置即为文件大小。
示例:
//将文件指针移动到文件末尾 SEEK_END + 0
fseek($handle, 0, SEEK_END);
//此时文件大小就等于指针的偏移量
$fileSize = ftell($handle);

19, basename

// 官网地址:https://www.php.net/manual/zh/function.basename.php
//返回路径中的文件名部分
示例:
echo basename(&#39;/etc/sudoers.d&#39;);   // sudoers ,注意没有文件的后缀名,和pathinfo($filePath)[&#39;filename&#39;]功能差不多

20, pathinfo

// 官网地址:https://www.php.net/manual/zh/function.pathinfo.php
//返回文件路径的信息
示例:
$pathParts = pathinfo(&#39;/etc/php.ini&#39;);
echo $pathParts[&#39;dirname&#39;] . PHP_EOL;     // /etc ,返回路径信息中的目录部分
echo $pathParts[&#39;basename&#39;] . PHP_EOL;  // php.ini ,包括文件名和拓展名
echo $pathParts[&#39;extension&#39;] . PHP_EOL; // ini ,拓展名
echo $pathParts[&#39;filename&#39;] . PHP_EOL;  // php ,只有文件名,不包含拓展名 ,和basename()函数功能差不多

21, headers_sent ($file, $line)

// 官网地址:https://www.php.net/manual/zh/function.headers-sent.php
//检测 HTTP 头是否已经发送
//1、http头已经发送时,就无法通过header()函数添加更多头信息,使用次函数起码可以防止HTTP头出错
//2、可选参数$file和$line不需要先定义,如果设置了这两个值,headers_sent()会把文件名放在$file变量,把输出开始的行号放在$line变量里

22, header ('$name: $value', $replace)

// 官网地址:https://www.php.net/manual/zh/function.header.php
//发送原生 HTTP 头
//1、注意:header必须在所有实际输出之前调用才能生效。
//2、header的$replace参数默认为true,会自动用后面的替换前面相同的头信息,如果设为false,则强制使相同的头信息并存
示例:
public function sendHeader()
{
    if (headers_sent($file, $line)) {
        throw new \Exception("Headers already sent in {$file} on line {$line}");
    }
    $headers = [
        &#39;Content-Type&#39; => [
            &#39;application/octet-stream&#39;,
            &#39;application/force-download&#39;,
        ],
        &#39;Content-Disposition&#39; => [
            &#39;attachment;filename=test.txt&#39;,
        ],
    ];
    foreach($headers as $name => $values) {
        //所有的http报头的名称都是首字母大写,且多个单词以 - 分隔
        $name = str_replace(&#39; &#39;, &#39;-&#39;, ucwords(str_replace(&#39;-&#39;, &#39; &#39;, $name)));
        $replace = true;
        foreach($values as $value) {
            header("$name: $value", $replace);
            $replace = false; //强制使相同的头信息并存
        }
    }
}

22. array_multisort ($array1, SORT_ASC|SORT_DESC, $array2)

// 官网地址:https://www.php.net/manual/zh/function.array-multisort.php
// 对多个数组或多维数组进行排序
//说明: $array1 : 排序结果是所有的数组都按第一个数组的顺序进行排列
//      $array2 : 待排序的数组

Example:

$array2 = [
    1000 => [
      &#39;name&#39; => &#39;张三&#39;,
      &#39;age&#39; => 25,
    ],
    1001 => [
      &#39;name&#39; => &#39;李四&#39;,
      &#39;age&#39; => 26,
    ],
];
//如果想将 $array2 按照 age 进行排序。
//不过需要注意的是:两个数组的元素个数必须相同,不然就会出现一个警告信息:
//Warning: array_multisort() [function.array-multisort]: Array sizes are inconsistent in ……
//第一步:将age的数据拿出来作为一个单独的数组,作为排序的依据。
$array1 = [];
foreach ($array2 as $key => $val) {
    array_push($array1, $val[&#39;age&#39;]);
}
//第二步骤:使用 array_multisort() 进行排序。
array_multisort($array1, SORT_DESC, $array2);
var_dump($array2);
//数组的健名字如果是数字会被重置,字符串不会
//        array (size=2)
//          0 =>
//            array (size=2)
//              &#39;name&#39; => string &#39;李四&#39; (length=6)
//              &#39;age&#39; => int 26
//          1 =>
//            array (size=2)
//              &#39;name&#39; => string &#39;张三&#39; (length=6)
//              &#39;age&#39; => int 2

23. strtr Convert the specified string

//官网文档:https://www.php.net/manual/zh/function.strtr.php
strtr(string $str , string $from , string $to )
strtr ( string $str , array $replace_pairs )
//例如:
$str = "<div class=&#39;just-sm-6 just-md-6&#39;><div class=&#39;control_text&#39;>{label}<font>*</font></div></div> <div class=&#39;just-sm-18 just-md-18&#39;><div class=&#39;control_element&#39;>{input} {hint} {error}</div></div>";
$parts = [
    &#39;{label}&#39; => &#39;年龄&#39;,
    &#39;{input}&#39; => &#39;<input name="age" id="user-age" class="inputs" value="" />&#39;,
    &#39;{hint}&#39; => &#39;年龄必须是 0-200 直接的数字&#39;,
    &#39;{error}&#39; => &#39;格式不正确&#39;,
];
$string = strtr($str, $parts);
echo htmlspecialchars($string); //<div class=&#39;just-sm-6 just-md-6&#39;><div class=&#39;control_text&#39;>年龄<font>*</font></div></div> <div class=&#39;just-sm-18 just-md-18&#39;><div class=&#39;control_element&#39;><input name="age" id="user-age" class="inputs" value="" /> 年龄必须是 0-200 直接的数字 格式不正确</div></div>
var_dump(Yii::getAlias(&#39;@webroot&#39;));
var_dump(Yii::getAlias(&#39;@web&#39;));

24. ReflectionClass report Relevant information about the class

//ReflectionClass  报告了一个类的有关信息
//官网地址:https://www.php.net/manual/zh/class.reflectionclass.php
//例如:
$class = new \ReflectionClass($this);
//打印当前类文件所在目录
var_dump(dirname($class->getFileName())); //var/www/html/basic/controllers

25. call_user_func_array Call the callback function and use an array parameter as the parameter of the callback function

//官网地址:https://www.php.net/manual/zh/function.call-user-func-array.php
function foobar($arg, $arg2) {
    echo __FUNCTION__, " got $arg and $arg2\n";
}
call_user_func_array("foobar", array("one", "two"));
//输出结果: foobar got one and two

The above is the detailed content of What are the advanced functions of php. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.