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

关于php foreach的参数问题

WBOY
Release: 2016-06-06 20:21:49
Original
1564 people have browsed it

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

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

回复内容:

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

当$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>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template