search
HomeBackend DevelopmentPHP TutorialSeveral 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.

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

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

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)