search
HomeBackend DevelopmentPHP Tutorial几道坑人的PHP面试题 试试看看你会不会也中招_php实例

这几道题是在德问上看到的,感觉挺有意思,拿来给大家分享其中的陷阱,看看你会不会掉入其中。

第一题

复制代码 代码如下:

$arr = array(0=>1,"aa"=>2, 3, 4);
 
foreach($arr as $key=>$val){
    print($key == "aa" ? 5 : $val);
}

输出结果是多少?如果的答案是1534就掉入陷阱了。
先看看这个数组最终形成的结构:
复制代码 代码如下:

Array
(
    [0] => 1
    [aa] => 2
    [1] => 3
    [2] => 4
)

然后遍历每一个元素的key看等不等于aa,等于就用5替代。当我告诉你答案是5534的时候,你会不会有点惊讶!难道0等于"aa"吗?是的,0就等于"aa",这道题重点就考你这个。在PHP中两个值进行逻辑判断时,如果两个值的类型不一致PHP会自动把右边的值转换到左边的类型,然后再进行判断。因此"aa"转换整形等于0,自然也就等于左边的0了。你可以使用全等于避免这种该情况,也就是如果你写成:
复制代码 代码如下:

print($key === "aa" ? 5 : $val);

那么答案就是1534了。

第二题

复制代码 代码如下:

$i='11';
printf("%d\n",printf("%d",printf("%d",$i)));

输出结果是多少?如果你回答是11,或者111111就掉入陷阱了。
先了解printf这个函数,printf不仅是打印函数,它还有返回值。重点就在这
复制代码 代码如下:

var_dump(printf("%d",$i));

你猜猜上面的结果是啥?先是printf打印变量本身11,然后printf会返回一个变量字符串长度的值,11有两个字符,于是返回2,于是上面语句的执行结果等于:
复制代码 代码如下:
11int(2)

清楚了这一点以后,再回过来看上面的试题,按照优先级,限制性深度printf函数,打印11,返回2。接着到第二级printf函数,打印2,返回1。最后到第三层,直接打印1,所以执行结果是 1121。

第三题

复制代码 代码如下:

$a = 3;
$b = 5;
if($a = 5 || $b = 7) {
    $a++;
    $b++;
}
echo $a . " " . $b;

执行结果是多少?如果你回答 6 8 or 4 6 or  6 6,那你就掉入陷阱了。
第一个陷阱,认为答案等于 4 6 。估计你粗心把  $a = 5 ||  $b = 7  看成 $a == 5 ||  $b == 7 ,这是新手常犯的错误。

第二个陷阱,认为答案等于 6 8。 你识破了  $a = 5 ||  $b = 7 这个骗局,但你没有注意到,逻辑或里只要依次执行直到某个表达式结果为true,表达式后边的就不再执行,$a = 5 返回true,后边的$b=7就不执行了。
第三个陷阱,认为答案等于 6 6。 OK,你识破了 逻辑或的规则,于是$a=5执行,$b=7不执行,但是你没有考虑到这里是逻辑表达式,返回给$a的值是要转换为布尔值的。这样看。

所以经过以上三个陷阱,你应该知道答案是多少了,其实 $a等于true以后,echo $a 输出就是1 ,$b值不变,结果就是 1 6 。

第四题

复制代码 代码如下:

$count = 5;
function get_count() {
    static $count = 0;
    return $count++;
}
++$count;
get_count();
echo get_count();

执行结果是多少?如果你回答 2 ,恭喜,你掉入陷阱了。
其实这道题主要考两点,第一点是static静态类型。这种的值永远都是静态的,第一次调用声明等于0,并且自增等于1。第二次调用,1再自增就等于2。但其实这里还有一道陷阱,那就是++a与a++的区别,前++是先自增,后++是先返回值再自增,所以结果等于 1。

第五题

复制代码 代码如下:

$a = count ("567")  + count(null) + count(false);
echo $a;

如果你回答 3 or 1,恭喜,掉入陷阱了。
因为count(null)等于0,false也算一个值。所以count(false)等于1。

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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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 Article

Hot Tools

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 Mac version

Dreamweaver Mac version

Visual web development tools

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment