search
HomeBackend DevelopmentPHP TutorialSummary of commonly used functions in PHP

Summary of commonly used functions in PHP

Mar 08, 2018 pm 03:59 PM
phpfunctionSummarize

PHP中函数的功能很强大,想必同学们应该都知道,在我们的PHP开发中运用到PHP函数是不可避免的,而我们常用的PHP函数你又知道哪些呢,我们一起来看看有哪些吧!

array_intersect()函数

比较两个数组的键值,并返回交集:

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
$result=array_intersect($a1,$a2);
print_r($result);
?>
result:Array ( [a] => red [b] => green [c] => blue )

array_keys() 函数

返回包含数组中所有键名的一个新数组。

<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");
print_r(array_keys($a));
?>
result:Array ( [0] => Volvo [1] => BMW [2] => Toyota )

array_key_exists() 函数

检查某个数组中是否存在指定的键名,如果键名存在则返回 true,如果键名不存在则返回 false。

<?php
    $a=array("Volvo"=>"XC90","BMW"=>"X5");
    if (array_key_exists("Volvo",$a))
      {
      echo "键存在!";
      }
    else
      {
      echo "键不存在!";
      }
?>

result:键存在!

array_merge() 函数

把两个数组合并为一个数组:

<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>

result:Array ( [0] => red [1] => green [2] => blue [3] => yellow )

array_reverse()函数

以相反的元素顺序返回数组:

<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
print_r(array_reverse($a));
?>

result:Array ( [c] => Toyota [b] => BMW [a] => Volvo )

array_unshift() 函数

用于向数组插入新元素。新数组的值将被插入到数组的开头。

<?php
$a=array("a"=>"red","b"=>"green");
array_unshift($a,"blue");
print_r($a);
?>

result:Array ( [0] => blue [a] => red [b] => green )

array_values函数

返回一个包含给定数组中所有键值的数组,但不保留键名。

<?php
$a=array("Name"=>"Bill","Age"=>"60","Country"=>"USA");
print_r(array_values($a));
?>

result:Array ( [0] => Bill [1] => 60 [2] => USA )

hash_equals 函数

可防止时序攻击的字符串比较
比较两个字符串,无论它们是否相等,本函数的时间消耗是恒定的。
本函数可以用在需要防止时序攻击的字符串比较场景中, 例如,可以用在比较 crypt() 密码哈希值的场景。

bool hash_equals ( string $known_string , string $user_string )

参数
known_string
已知长度的、要参与比较的 string
user_string
用户提供的字符串

返回值:
当两个字符串相等时返回 TRUE,否则返回 FALSE。

<?php
$expected  = crypt(&#39;12345&#39;, &#39;$2a$07$usesomesillystringforsalt$&#39;);
$correct   = crypt(&#39;12345&#39;, &#39;$2a$07$usesomesillystringforsalt$&#39;);
$incorrect = crypt(&#39;apple&#39;,  &#39;$2a$07$usesomesillystringforsalt$&#39;);

var_dump(hash_equals($expected, $correct));
var_dump(hash_equals($expected, $incorrect));
?>

result:
bool(true)
bool(false)

in_array() 函数

搜索数组中是否存在指定的值。

<?php
$people = array("Bill", "Steve", "Mark", "David");

if (in_array("Mark", $people))
  {
  echo "匹配已找到";
  }
else
  {
  echo "匹配未找到";
  }
?>

result:匹配已找到

sprintf() 函数

把百分号(%)符号替换成一个作为参数进行传递的变量:

<?php
    $number = 2;
    $str = "Shanghai";
    $txt = sprintf("There are %u million cars in %s.",$number,$str);
    echo $txt;
?>

result:There are 2 million cars in Shanghai.

str_ireplace() 函数

替换字符串中的一些字符(不区分大小写) str_ireplace(find,replace,string,count)

<?php
echo str_ireplace("WORLD","Shanghai","Hello world!");
?>

result:Hello Shanghai!

strpos 函数

查找字符串在另一字符串中第一次出现的位置。

<?php
echo strpos("You love php, I love php too!","php");
?>

result:9

str_replace() 函数

以其他字符替换字符串中的一些字符(区分大小写)

<?php
echo str_replace("world","Shanghai","Hello world!");
?>

result:Hello Shanghai!

str_ireplace() 函数
替换字符串中的一些字符(不区分大小写)
str_ireplace(find,replace,string,count)

<?php
echo str_ireplace("WORLD","Shanghai","Hello world!");
?>

result:Hello Shanghai!

substr 函数

返回字符串的一部分。

<?php
echo substr("Hello world",6);
?>

result:world

以上就是我们在PHP开发中常用到的PHP函数。

更多PHP常用函数

180多个PHP常用函数总结

The above is the detailed content of Summary of commonly used functions in 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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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

Video Face Swap

Video Face Swap

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

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools