note 99957 added to function.return
| From: | (at) | Date: | Thu, 16 Sep 2010 16:23:41 +0000 |
| Subject: | note 99957 added to function.return | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-172658@lists.php.net to get a copy of this message | ||
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).
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:
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;
}
}
----
Server IP: 64.71.164.2
Probable Submitter: 138.23.171.29
----
Manual Page -- http://www.php.net/manual/en/function.return.php
Edit -- https://master.php.net/note/edit/99957
Del: integrated -- https://master.php.net/note/delete/99957/integrated
Del: useless -- https://master.php.net/note/delete/99957/useless
Del: bad code -- https://master.php.net/note/delete/99957/bad+code
Del: spam -- https://master.php.net/note/delete/99957/spam
Del: non-english -- https://master.php.net/note/delete/99957/non-english
Del: in docs -- https://master.php.net/note/delete/99957/in+docs
Del: other reasons-- https://master.php.net/note/delete/99957
Reject -- https://master.php.net/note/reject/99957
Search -- https://master.php.net/manage/user-notes.php