« Where Comments Are Useful | For The Love Of God, Use Keys! » |
Sometimes I have to check an array for the existence of a value; for example, I may want to parse an array for a value and then include (or exclude) that value fro an SQL query. I quickly found out that using in_array() is slower than using isset(). For example:
<?php $exclude = array( 'submit', 'go', 'do', ); foreach($_POST as $k => $v) { if(in_array($k,$exclude)) unset($_POST[$k]); } ?>
In the above example, in_array() must walk the entire length of the array to check for the value, which may (or may not) be there. However, if we use isset() it doesn’t have to do that. We just have to write our array a bit differently:
<?php $exclude = array( 'submit' => true, 'go' => true, 'do' => true, ); foreach($_POST as $k => $v) { if(isset($array[$k])) unset($_POST[$k]); } ?>
On large arrays, this has the benefit of being faster (though not more elegant). In the event that you need to put valid data in the “value” portion of the array you can duplicate the data if necessary (though this does slow it down somewhat but not considerably).
Brandon Savage is the author of Mastering Object Oriented PHP and Practical Design Patterns in PHP
Posted on 12/22/2008 at 6:56 pm
jack wrote at 4/22/2009 1:39 pm:
Hi Brandon,
Just browsing around and came across your other post on superglobals in classes, then this one.
In the code above, the isset() call is redundant. Since you are setting the value to true, the following also works:
if ($array[$k])
unset($_POST[$k]);On large arrays, this is MUCH faster than the in_array() method and — I’d have to disagree with you — more elegant, too.
For large arrays, you can always create the array normally and then use the array_flip() method to exchange the keys and values. You just have to be careful with the zero array element, but that’s easy to get around by starting your array indexes at one:
$array = array(1 => ‘somevalue’, ‘othervalue’, ‘newvalue’…);
The indexes for othervalue, newvalue, etc… will now be 2, 3… You can then use array_flip() to exchange the keys and values in the array. Since any number, other than zero, evaluates to true, the if statement above will still work.
–jack
Brandon Savage (@brandonsavage) wrote at 4/22/2009 1:43 pm:
Jack, I have to disagree with your code sample. Simply doing if($array[$k]) will emit a notice if the array key does not exist. My code sample was designed to prevent this notice from being emitted. If you turn errors to E_ALL you’ll see this notice, which I think we can both agree would slow down service of the site while the web server writes to the error logs.
Rory wrote at 7/13/2009 9:18 pm:
This post is old but people never make use of all the great built-in array functions:
$exclude = array(‘submit’ => true, ‘go’ => true);
$valid = array_diff_key($_POST, $exclude);
« Where Comments Are Useful | For The Love Of God, Use Keys! » |