note 99957 deleted from function.return by danbrown
| From: | danbrown@php.net | Date: | Sat, 06 Nov 2010 23:29:35 +0000 |
| Subject: | note 99957 deleted from function.return by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-173819@lists.php.net to get a copy of this message | ||
Note Submitter: smhlambi (at) cs dot *ucr* dot edu
----
This is for mostly the newbies. If you create a function and you want it to either return false or
true then you must explicitly state it. I know this should go without saying. But it's better
explained with an example.
I'm looking through an array to see if the contents of the array mismatch ( ex: email
verification).
<?php
function check_array()){
foreach($array as $key => $value){
if($value != $match){
echo "The email fields don't match!";
return; // this by default returns false.
}
}
}
?>
Now what if the array I pass this time is valid and the contents of it match? Then the function
check_array() should return true right? not so fast.If I still call this function it will still
return false and thus cause unexpected results.
It's not like the typical: if(function_name()) echo "i know this is true"; else
echo"this has to be false";
Instead when using the return and say: if(check_array()) echo " then this part will never
execute because return is always false"; else "but this part will always execute but
return false, even if the array contents match simply because return is always false";
If I want it to return true when the array contents all match then I must explicitly add the else
statement: else return true;
like this:
<?php
function check_array()){
foreach($array as $key => $value){
if($value != $match){
echo "The email fields don't match!";
return; // this by default returns false.
}else return true;
}
}
?>