


Several pitfalls encountered in PHP interview questions. wall-facing
1.Pointer hanging problem
$array = [1, 2, 3];
echo implode(',', $array), "n";
foreach ($array as &$value) { } // by reference
echo implode(',', $array), "n";
foreach ($array as $value) {} // by value (i.e., copy)
echo implode(', ', $array), "n";
The correct answer should be:
1,2,3
1,2,2
Explanation:
Let’s analyze it. After the first loop, $value is a reference to the last element in the array. The second loop begins:
Step 1: Copy $arr[0] to $value (note that at this time $value is $arr[2] Reference), then the array becomes [1,2,1]
Step 2: Copy $arr[1] to $value, then the array becomes [1 ,2,2]
Step 3: Copy $arr[2] to $value, then the array becomes [1,2,2]
2. or below Result output:
$test=null;
if(isset($test)){
echo "true";
}else{
echo "false";
}
?>
Correct answer: false
Explanation: For the isset() function, it will return false when the variable does not exist, and it will also be returned when the variable value is null false.
To determine whether a variable is actually set (to distinguish between unset and set values null), the array_key_exists() function may be better.
3. Can the following results be printed and why?
class Config{
private $values = [];
public function getValues() {
return $this->values;
}
}
$ config = new Config();
$config->getValues()['test'] = 'test';
echo $config->getValues()['test'];
Correct answer:
No, because in PHP In , unless you explicitly specify a return reference, for the array PHP is a value return, which is a copy of the array. Therefore, when the above code assigns a value to the returned array, it actually assigns a value to the copied array, not the original array. If you change the code to:
class Config{
private $values = [];
// return a REFERENCE to the actual $values array
public function &getValues() {
Return $this-> values;
}
}
$config = new Config();
$config->getValues()['test'] = 'test';
echo $config->getValues()[ 'test'];
is fine.
Knowledge points: In PHP, for objects, the default is to return by reference, and arrays and built-in basic types are returned by value by default. This should be distinguished from other languages (many languages pass arrays by reference).
4. What does the server output after running the following code?
$.ajax({
url: 'http://my.site/ndex.php',
method: 'post',
data: JSON.stringify({a: 'a', b: 'b'}),
contentType: 'application/json'
});
var_dump($_POST);
Answer: array(0){}
Explanation: PHP only parses Content-Type for application/x-www-form-urlencoded or multipart/form-data for Http requests. The reason for this is for historical reasons. When PHP was first implemented $_POST, the above two types were the most popular. Therefore, although some types (such as application/json) are very popular now, automatic processing is still not implemented in PHP. Because $_POST is a global variable, changing $_POST will be globally effective. Therefore, for requests whose Content-Type is application/json , we need to manually parse the json data, and then modify the $_POST variable.
$_POST = json_decode(file_get_contents('php://input'), true);
This explains why WeChat public platform development also uses this method to obtain the data of WeChat server post
6. The output result of the following code is:
for ($c = 'a'; $c
echo $c . "n";
}
Correct Answer: a..........z,aa....yz
Explanation: There is no chardata type in PHP, only the stringtype. Understand this, then perform an increment operation on 'z', and the result will be 'aa'. Regarding string size comparison, those who have learned C should all know that 'aa' is smaller than 'z'. This also explains why there is the above output result.
But in PHP, if you compare two purely numeric strings, you first try to compare them as numbers.
Copyright Statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.
The above introduces several pitfalls encountered in PHP interview questions. Face the wall ing, including the content, I hope it will be helpful to friends who are interested in PHP tutorials.

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

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

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

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.

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

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.

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.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)
