Home  >  Article  >  Backend Development  >  关于php foreach的参数问题

关于php foreach的参数问题

WBOY
WBOYOriginal
2016-06-06 20:21:491517browse

<code>$arr = array();
foreach ($arr as $key => $value) {
    if (!isset($key)) {
        echo 'haha';
    }
}</code>

当$key不存在的时,输出haha,但是实际操作为什么什么也没有输出?

回复内容:

<code>$arr = array();
foreach ($arr as $key => $value) {
    if (!isset($key)) {
        echo 'haha';
    }
}</code>

当$key不存在的时,输出haha,但是实际操作为什么什么也没有输出?

没有进入foreach

$key 不存在是怎么被遍历到的?

逻辑问题,肯定进不了if

首先array为空,不会进入foreach,其次,不会存在!isset($key)的情况

楼上说的对,你的array都是为空的,程序都不会进入foreach循环。

$arr有值,也不会进入if

<code class="php">$arr = array('key1'=>'hello',3,4=>'34',4);
foreach ($arr as $key => $value) {
    if (!isset($key)) {
        echo 'haha';
    }else{
        echo $key.' ';
    }
}
//print: key1 0 4 5</code>
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