Home Backend Development PHP Problem What are the advanced functions of php

What are the advanced functions of php

Nov 14, 2019 am 11:52 AM
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
Copy after login

2、get_class

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

3.get_called_class

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

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) }
Copy after login

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;
Copy after login

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" }
Copy after login

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)
Copy after login

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
    }
}
Copy after login

9, passthru

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

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) }
    }
}
Copy after login

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);   //原数组不变
Copy after login

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的语法
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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;);
Copy after login

17, fseek

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

18, ftell

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

19, basename

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

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()函数功能差不多
Copy after login

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变量里
Copy after login

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; //强制使相同的头信息并存
        }
    }
}
Copy after login

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

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

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
Copy after login

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;));
Copy after login

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
Copy after login

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
Copy after login

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 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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles