search
HomeBackend DevelopmentPHP TutorialThe latest summary of PHP interview questions and answers

This article will share with you the latest summary of PHP interview questions and answers. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Related recommendations: "The latest summary of application questions for PHP interview questions""The latest summary of PHP interview questions for conceptual questions"

1. The difference between echo(), print() and print_r()

echo() and print() are PHP statements; print_r() is a function,

  • print() can only print out the value of simple type variables (such as int, string) and has a return value.
  • print_r() can print out the value of complex type variables (such as arrays, objects)
  • echo outputs one or more strings, no return value
  • Single quotes cannot interpret variables, while double quotes can interpret variables.
  • Single quotes cannot escape characters, but characters can be escaped within double quotes.

3. Error_reporting function

error_reporting() sets the error level of PHP and returns the current level.

4. The difference between SESSION and COOKIE

  • session is stored on the server side, and cookie is stored on the client side.

  • Session is relatively safe, but cookies can be modified by certain means, which is not safe.

  • The running of session depends on the session id, and the session id is stored in the cookie. If cookies are disabled, the session will become invalid. (But it can be achieved in other ways, such as passing the session id in the url).

  • session can be placed in a file, database or memory. By default it is stored in a file on the server.

5. The difference between get and post

get is explicit, the data can be seen from the url, and the amount of data transferred is small , low security;

post is implicit, the amount of data transmitted is large, and security is high.

6. Write the execution result of the following code

<?php     $a = 12;
    $b = 012;
    $c = 0x12;
    echo $a,"\n",$b,"\n",$c;

Analysis: octal 12 is converted to binary 001010, and binary is converted to decimal 10. Hexadecimal 12 is converted to binary 00010010, and binary is converted to decimal 18. So the result is 12 10 18.

7. Solve the problem of Chinese garbled characters in url

Use urlencode() to encode Chinese.

8. Convert the string in GB2312 format to UTF-8

iconv('GB2312','UTF-8','悄悄是别离的笙箫');

9. Convert the string into an array

$str = "hello word;From-ajiang";str_split($str, 3);
explode(";", $str);preg_split("/-/", $str);

10. String replacement function

$str = 'linux and php';
str_replace('linux', 'windows', $str);
preg_replace('/linux|php/', 'js', $str);

11. String search function

preg_match("/php/i", "PHP is the web scripting language of choice.");
$userinfo = "Name: <b>PHP</b> <br> Title: <b>Programming Language</b>";
preg_match_all ("/<b>(.*)/U", $userinfo, $pat_array);
strpos("I love php, I love php too!","php");   // 首次匹配的位置
strrpos("I love php, I love php too!","php");  // 最后匹配的位置</b>

12. Using redis What are the benefits

  • Fast speed: Because the data is stored in memory, similar to HashMap, the advantage of HashMap is that the time complexity of search and operation is O(1).

  • Support rich data types: support string, list, set, sorted set, hash.

  • Support transactions: multiple commands can be executed at one time. Failure will not roll back and execution will continue.

  • Rich features: can be used for caching, messaging, setting expiration time by key, it will be automatically deleted after expiration

13. What are the advantages of redis compared to memcached

  • All values ​​in memcached are simple strings, and redis, as its replacement, supports richer data types.

  • redis is much faster than memcached.

  • redis can persist its data

14. Run the PHP script on the command line and pass parameters

First enter the PHP installation directory. The -f parameter specifies the PHP file to be executed. The parameters are directly connected after the file name. Multiple parameters are separated by spaces. -r means to execute php code directly.

If arguments are passed, the script will first check $argc to ensure that the number of arguments meets the requirements. Then each argument is extracted from $argv and printed to standard output.

$ php -f d:/wamp/test.php [参数1 参数2 ...] $ php -r phpinfo();

15. crontab scheduled task syntax

Program executed in minutes, hours, days, months and weeks

案例: 一个备份程序mybackup,需要在周一到周五下午1点和晚上8点运行,命令如下:

 0 13,20 * * 1,2,3,4,5 mybackup // 或 0 13,20 * * 1-5 mybackup

16. 键入网址再按下回车

  • 浏览器从地址栏的输入中获得服务器的 IP 地址和端口号;

  • 浏览器用 TCP 的三次握手与服务器建立连接;

  • 浏览器向服务器发送拼好的报文;

  • 服务器收到报文后处理请求,同样拼好报文再发给浏览器;

  • 浏览器解析报文,渲染输出页面。

17. php 数组相关的函数

array_combine()-----通过合并两个数组来创建一个新数组
array_chunk()-------将一个数组分割成多个
array_merge()-------把两个或多个数组合并成一个数组
array_slice()-------在数组中根据条件取出一段值
array_diff()--------返回两个数组的差集数组
array_intersect()---计算数组的交集
array_search()------在数组中搜索给定的值
array_splice()------移除数组的一部分且替代它
array_key_exists()--判断某个数组中是否存在指定的key
array_flip()--------交换数组中的键和值
array_reverse()-----将原数组中的元素顺序翻转,创建新的数组并返回
array_unique()------移除数组中重复的值
range()-------------创建并返回一个包含指定范围的元素的数组

18. PHP 数组排序

sort()   - 以升序对数组排序
rsort()  - 以降序对数组排序
asort()  - 根据值,以升序对关联数组进行排序
ksort()  - 根据键,以升序对关联数组进行排序
arsort() - 根据值,以降序对关联数组进行排序
krsort() - 根据键,以降序对关联数组进行排序

19. $_SERVER

// http://www.test.com/testA/test?name=aj&age=23
"HTTP_HOST" => "www.test.com"
"SERVER_NAME" => "www.test.com"
"SERVER_PORT" => "80"               // 服务器端口
"SERVER_ADDR" => "127.0.0.1"        // 服务器IP
"REMOTE_PORT" => "13675"            // 客户端IP
"REMOTE_ADDR" => "127.0.0.1"        // 客户端口
"REQUEST_URI" => "/testA/test?name=aj&age=23"          // 参数
"SCRIPT_NAME" => "/index.php"
"QUERY_STRING" => "s=//testA/test&name=aj&age=23"
"SCRIPT_FILENAME" => "F:/projectName/public/index.php" // 当前执行脚本路径

20. 魔术方法

__construct(),类的构造函数
__destruct(),类的析构函数

__call(),在对象中调用一个不可访问方法时调用
__callStatic(),用静态方式中调用一个不可访问方法时调用

__get(),获得一个不存在的类成员变量时调用
__set(),设置一个不存在的类成员变量时调用

__isset(),当对不可访问属性调用isset()或empty()时调用
__unset(),当对不可访问属性调用unset()时被调用。

__sleep(),执行serialize()时,先会调用这个函数
__wakeup(),执行unserialize()时,先会调用这个函数
__toString(),类被当成字符串时的回应方法

__invoke(),调用函数的方式调用一个对象时的回应方法
__set_state(),调用var_export()导出类时,此静态方法会被调用。

__clone(),当对象复制完成时调用
__autoload(),尝试加载未定义的类
__debugInfo(),打印所需调试信息

21. PHP 的基本变量类型

  • 四种标量类型:boolean (布尔型)、integer (整型)、float (浮点型, 也称作 double)、string (字符串)
  • 两种复合类型:array (数组)、object (对象)
  • 两种特殊类型:resource(资源)、NULL(NULL)


本文章首发在 LearnKu.com 网站上。

The above is the detailed content of The latest summary of PHP interview questions and answers. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function