note 105178 modified in function.in-array by danbrown
| From: | danbrown@php.net | Date: | Mon, 01 Aug 2011 16:25:52 +0000 |
| Subject: | note 105178 modified in function.in-array by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-182076@lists.php.net to get a copy of this message | ||
Be VERY careful about testing for strings in arrays that might also contain integers. In this
snippet, the range() function turns the numeric values into integers, and loose data typing finds a
match with zero.
Outputs:
PHP in_array() FOUND @#%?!!
@#%?!! == 0 AT POSITION 26 BECAUSE OF LOOSE TYPE
<?php // RAY_temp_in_array.php
error_reporting(E_ALL);
echo "<pre>";
// THE ALLOWABLE SELECTIONS
$alpha = range('A','Z');
$alpha = array_merge($alpha, range('0', '9'));
// LOOK FOR A BOGUS SELECTION
$str = '@#%?!!';
if (in_array($str, $alpha))
{
echo "PHP in_array() FOUND $str ";
}
else
{
echo "$str IS NOT IN ARRAY";
}
// SEARCH THE ARRAY FOR THE KEY OF THE STRING
$key = array_search($str, $alpha);
echo "<br/>$str == $alpha[$key] AT POSITION $key";
if ($str == 0) echo " BECAUSE OF LOOSE TYPE";
?>
--was--
Be VERY careful about testing for strings in arrays that might also contain integers. In this
snippet, the range() function turns the numeric values into integers, and loose data typing finds a
match with zero.
Outputs:
PHP in_array() FOUND @#%?!!
@#%?!! == 0 AT POSITION 26 BECAUSE OF LOOSE TYPE
<?php // RAY_temp_in_array.php
error_reporting(E_ALL);
echo "<pre>";
// THE ALLOWABLE SELECTIONS
$alpha = range('A','Z');
$alpha = array_merge($alpha, range('0', '9'));
// LOOK FOR A BOGUS SELECTION
$str = '@#%?!!';
if (in_array($str, $alpha))
{
echo "PHP in_array() FOUND $str ";
}
else
{
echo "$str IS NOT IN ARRAY";
}
// SEARCH THE ARRAY FOR THE KEY OF THE STRING
$key = array_search($str, $alpha);
echo "<br/>$str == $alpha[$key] AT POSITION $key";
if ($str == 0) echo " BECAUSE OF LOOSE TYPE";
http://php.net/manual/en/function.in-array.php