开发者

Processing SQL response from multi-dimentional array

开发者 https://www.devze.com 2023-03-27 07:13 出处:网络
Each row of SQL request returns multi-dimentional array with only 1 element \"active\" now when I do this it outputs even part of array that is \"0\" as well

Each row of SQL request returns multi-dimentional array with only 1 element "active" now when I do this it outputs even part of array that is "0" as well

for ($i = 0; $i < count($sql_response); $i++) {
    foreach ($sql_response[$i] as 开发者_StackOverflow社区$key => $value) {
        if ($key == "active"){
            echo "<br>".$key." - ".$value;
        };
    };
};

If I use === in IF it works, why it does not work with == it seems like i never had this problem with single denominational arrays.


If $sql_response contains something like:

array(
    0 => "value",
    "active" => "value"
)

then the foreach statement will go through both elements, first assigning 0 to $key, then assigning "active" to key.

$key == "active" will return true when $key is 0, because:

  • it compares 0 == "active"
  • which casts "active" to integer so it can be compared with 0
  • which results in 0 == 0
  • which is true

If you're using the mysql_* or mysqli_* functions to obtain $sql_response, then to prevent adding the numeric keys to the result array, use mysql_fetch_assoc or mysqli_fetch_assoc instead of their *_fetch_array counterparts.

0

精彩评论

暂无评论...
验证码 换一张
取 消