开发者

PHP Associative array

I have an array as

$arrTest = array('val1','val2','val3','val4');
$arrTest['lastKey'] = 'Last Key';
foreach($arrTest as $key => $val) {
  if($key == 'lastKey') {开发者_高级运维
     echo "last found";
  }
}

The above code is not working. I have added associative element in the array. Could it be the reason?


Change == to === in:

if($key == 'lastKey')

Your existing code echos last found twice, once for key 0 and once for key lastKey.

Comparing integer 0 and string 'lastKey' using == returns true !!

From the PHP manual:

String conversion to numbers

When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

The string will be evaluated as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will be evaluated as an integer.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.


Use === to compare. Because when key 0 will be compared with string lastKey, string will be converted to integer and false result will be returned.
http://codepad.org/5QYIeL4f

$arrTest = array('val1','val2','val3','val4');
$arrTest['lastKey'] = 'Last Key';
foreach($arrTest as $key => $val) {
  if($key === 'lastKey') {
     echo "last found";
  }
}

Read more about differences: http://php.net/manual/en/language.operators.comparison.php


You need to change your equality condition to check the type as well.

if($key === 'lastKey')

This is because PHP evaluates ' ' == 0 as true.


When I ran your code, 'last found' was outputted twice. 'lastKey' is evaluated to 0 in PHP, so if($key == 'lastKey') actually matches twices: once for 0 and once for your special element.


use the end() function to get the last key of an array and compare it in your if statement.

$arrTest = array('val1','val2','val3','val4');
$lastKey = end($arrTest);
foreach($arrTest as $key => $val) {
  if($val == $lastKey) {
     echo "last found";
  }
}


Your code is working fine : see it here : http://codepad.org/hfOFHMnc

However use "===" instead of "==" as you might encounter a bug when comparing the string with 0 , and it will echo twice.

<?php

$arrTest = array('val1','val2','val3','val4');
$arrTest['lastKey'] = 'Last Key';
print_r($arrTest);

foreach($arrTest as $key => $val) {
  if($key == 'lastKey') {       // use === here
     echo "key = $key   :: last found \n";
  }
}


If you want to test if an array key exists, simply use array_key_exists:

array_key_exists('lastKey', $arrTest)

You could also use isset but note that it returns false if the value associated to the key is null.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜