search
HomeBackend DevelopmentPHP TutorialSummarize the scattered knowledge points in PHP

Summarize the scattered knowledge points in PHP

Aug 13, 2017 pm 02:36 PM
phpKnowledge points

Today I will share with you the trivial knowledge points of PHP. It is very good and has reference value. Friends who need it can refer to it

PHP will not check single quotes'' Variable interpolation in strings Or (almost) any escape sequence, so defining a string using single quotes is fairly simple and fast. However, this is not the case with double quotes "". PHP will check the variables or escape sequences in the string and output the values ​​of the variables and escape sequences.


$a = "123";
print '$a\t';
print '$a';

Output:


##

$a\t$a

If it is a double quote "" :



$a = "123";
print "$a\t";
print "$a";

Output:

Note:

Single quotes'' can be interpreted '\ and \\ are the two escape characters, that's all!

can use single quotes as much as possible for single quote characters. Single quotes are more efficient than double quotes (because double quotes must be traversed first to determine whether there are variables in them before operating, while single quotes are not requires judgment).

Single quotes '' and double quotes "" can be used

The difference between echo and print:

This Both are statements, not functions; the function of these two statements is to output strings. However:

echo can pass in multiple parameters. There is only one print:



echo "123", "123";//输出123123
print "123", "123";//报错,只可以写一个参数 print "123";

echo has no return value, while the print return value is always 1;

Note :

The eight data types of PHP, except arrays and objects that do not implement the __toString magic function, can be output by echo or print, and boolean types can be output by echo or print. Output will only display 1 or not.



echo true; //输出1
echo false; //什么都不输出

Add numbers and strings:

PHP will automatically complete the string and digital conversion, which sometimes brings benefits, sometimes it is very distressing.



echo 1 + "2";//输出3
echo 1 + "a";//输出1

$a = 1 + "A"; What is the data type of variable $a?



if(is_numeric($a)){
  echo "是整型";
}
else{
  echo "是其他类型";
}
//最后输出:是整型

The difference between the random number generation function rand() and mt_rand(): ## The usage of #rand() and mt_rand() are exactly the same. They have two usages respectively:


//第一种用法:
rand();//产生的随机数为0到getrandmax()之间
mt_rand();//产生的随机数为0到mt_getrandmax()之间
//第二种用法:
rand($min, $max);//产生从$min到$max之间的随机数
mt_rand($min, $max);//产生从$min到$max之间的随机数

Difference: mt_rand() is a better random number Generator, because it sows a better random number seed than rand(); and the performance is 4 times faster than rand(), and the range of values ​​represented by mt_getrandmax() is also larger

The difference between the BCMath library and the GMP library: The BCMath library is easy to use. Pass numbers into the function as strings and it will return the sum (or difference, product, etc.) of the numbers as a string. However, when using BCMath, the operations that can be performed on numbers are limited to basic arithmetic operations.


$sum = bcadd("12345678", "87654321");//$sum = "99999999"

GMP functions can accept integers or strings as parameters, but they prefer to pass numbers as resources, which actually point to the internal representation of the number. pointer. So unlike the BCMath function, which returns a string, GMP only returns the resource. This resource can be passed as a number to any GMP function.


$four = gmp_add(2, 2);//可以传入整数
$eight = gmp_add('4', '4');//或字符串
$twelve = gmp_add($four, $eight);//或GMP资源

The only disadvantage of GMP is that when you want to view or use resources with non-GMP functions, you need to use gmp_strval() or gmp_intval() to explicitly convert .

Note BCMath is bundled with PHP. If GMP is not bundled with PHP, you need to download and install it separately. Another option for accomplishing high-precision math operations is to use PECL's big_int library.

The difference between include and require: include() and require() statements include and run the specified file. The two structures are exactly the same in the include files. The only difference is the error handling:


•require() statement will stop when it encounters that the included file does not exist or an error occurs. , and report an error.

•include() When encountering an included file that does not exist, it only generates a warning and the script continues.


In other words, if you want to stop processing the page when a file is missing, don't hesitate to use require(). This is not the case with include() and the script will continue to run.

include_once and require_once
•include_once() is the same as require_once() and should be used on the same file during script execution When it is possible to be included more than once, you want to ensure that it is only included once to avoid problems such as function redefinition and variable reassignment. This is the main difference between include_once() and require_once() and include() and require().

•require_once() and include_once() are less efficient than require() and include() because the first two need to determine whether the file to be imported already exists. `


The difference between PHP merging array + and array_merge()

同为数组合并,但是还是有差别的:

•键名为数字时,array_merge()不会覆盖掉原来的值,但+合并数组则会把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉(不是覆盖)


$a = array('a','b'); 
$b = array('c', 'd'); 
$c = $a + $b; 
var_dump($c);
//输出:
// array (size=2)
// 0 => string 'a' (length=1)
// 1 => string 'b' (length=1) 
var_dump(array_merge($a, $b));
//输出:
//array (size=4)
// 0 => string 'a' (length=1)
// 1 => string 'b' (length=1)
// 2 => string 'c' (length=1)
// 3 => string 'd' (length=1)

•键名为字符时,+仍然把最先出现的键名的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉,但array_merge()此时会覆盖掉前面相同键名的值


$a = array('a' => 'a' ,'b' => 'b');
$b = array('a' => 'A', 'b' => 'B');
$c = $a + $b;
var_dump($c);
//输出:
//array (size=2)
//'a' => string 'a' (length=1)
//'b' => string 'b' (length=1)
var_dump(array_merge($a, $b));
//输出:
//array (size=2)
//'a' => string 'A' (length=1)
//'b' => string 'B' (length=1)

字符串常用函数

PHP提供了很多方便的字符串函数,常用的有:

•strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] ) 。返回 haystack 字符串从 needle 第一次出现的位置开始到 haystack 结尾的字符串。若为before_needle为 TRUE,strstr() 将返回 needle 在 haystack 中的位置之前的部分。
•substr( string $string , int $start [, int $length ] ) 。返回字符串 string 由 start 和 length 参数指定的子字符串。
•substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] ) 。substr_replace() 在字符串 string 的副本中将由 start 和可选的 length 参数限定的子字符串使用 replacement 进行替换。
•strrev ( string $string ) 。返回 string 反转后的字符串。
•str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) 。该函数返回一个字符串或者数组。该字符串或数组是将 subject 中全部的 search 都被 replace 替换之后的结果。subject为执行替换的数组或者字符串。也就是 haystack。如果 subject 是一个数组,替换操作将遍历整个 subject,返回值也将是一个数组。如果count被指定,它的值将被设置为替换发生的次数。
•strpos ( string $haystack , mixed $needle [, int $offset = 0 ] ) 。返回 needle 在 haystack 中首次出现的数字位置;如果提供了offset参数,搜索会从字符串该字符数的起始位置开始统计。 如果是负数,搜索会从字符串结尾指定字符数开始。
•ltrim() 、 rtrim() 、 trim() 。这仨都是删除字符串中的空白符。 ltrim() 删除字符串开头的空白字符; rtrim() 删除字符串末端的空白字符; trim() 去除字符串首尾处的空白字符。 

The above is the detailed content of Summarize the scattered knowledge points 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 dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

PHP Dependency Injection: Boost Code MaintainabilityPHP Dependency Injection: Boost Code MaintainabilityMay 07, 2025 pm 02:37 PM

Dependency injection provides object dependencies through external injection in PHP, improving the maintainability and flexibility of the code. Its implementation methods include: 1. Constructor injection, 2. Set value injection, 3. Interface injection. Using dependency injection can decouple, improve testability and flexibility, but attention should be paid to the possibility of increasing complexity and performance overhead.

How to Implement Dependency Injection in PHPHow to Implement Dependency Injection in PHPMay 07, 2025 pm 02:33 PM

Implementing dependency injection (DI) in PHP can be done by manual injection or using DI containers. 1) Manual injection passes dependencies through constructors, such as the UserService class injecting Logger. 2) Use DI containers to automatically manage dependencies, such as the Container class to manage Logger and UserService. Implementing DI can improve code flexibility and testability, but you need to pay attention to traps such as overinjection and service locator anti-mode.

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

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.