When I've read PHP tutorials and you've got a list of values you want to check a variable against, the values are usually in an array, and a loop is used to check the variable against each value.
For example, we'll look at this block of code, assuming that $userin is user input...
$people = array("fred","wilma","barney","betty","pebbles","bam bam");
$match=false;
for($i=0;$i<count($people);$i++){
if($people[$i]==$userin) $match = true;
}
if ($match) {whatever code you'd execute if there was a match}
That's all well and good, but it's more code than you need. Let's look at an optimized version...
$people = array("fred"=>1,"wilma"=>1,"barney"=>1,"betty"=>1,"pebbles"=>1,"bam bam"=>1);
if (isset($people[$userin])) {whatever code you'd execute if there was a match}
Instead of setting the names as values in an array, you've set them as keys in an associative array. Then, instead of iterating through all the values of the array, checking each value against the user input, all you need to do is check whether the user input value exists as a key in the array using the isset() function. This basically cuts out that entire loop in the middle and brings you from six lines of code to two.
If you ever need to iterate through the array, you use a for each loop.
Simple as that.

Entries (RSS)