For some odd reason my PHP is not seeing the value of the second parameter.
My code:
PHP function:
public function getVacs($key, $id = null, $deleted = null, $deleted_key = null) {
if(!$id) {
$data = $this->_db->getAll('vacatures', $key);
} elseif(!empty($deleted)) {
$data = $this->_db->getAll('vacatures', $key, $id, $deleted, $deleted_key);
} else {
$data = $this->_db->getAll('vacatures', $key, $id);
}
if($data->count()) {
$this->_data = $data->results();
$this->_count = $data->count();
return true;
}
}
Calling the function:
} elseif(isset($_POST['all'])) {
$vacs = $v->getVacs('delete', '0');
echo json_encode($v->data());
exit();
}
The problem is, the function does not see the value of $id.
It's running the first if while it should be running the else.
In php the string "0" evaluates to false.
This means your check if(!$id) will evaluate to true and by your logic id won't be set in $data.
If the string "0" is legitimate option, then check for null explicitly instead:
if(is_null($id)){
This will
It is seeing the value of $id, but your if statement is set up wrong. 0 will evaluate to false on a check like that. So you really need to make sure that it's not null:
if($id != null) {
If you want the first if to run only if there is NOT a valid id, then you need to check if it's empty (i.e. not null, 0, false, or an empty string)
if(empty($id)) {
Using the strict comparison operator might be a good idea in these cases (and I would say in most cases):
0 == null; // evaluates to true
0 === null; // evaluates to false
Useful with strpos also (returns 0 means searched term at position 0 of haystack string, returns false means searched term not found).
Related
I am calling API through postman and passing following parameters.
reason: string
staff_ids[]:
When pass staff_ids blank then I got [null] in server-side.
so that the condition gets always true.
if(isset($request->staff_ids) && !empty($request->staff_ids)){
//
}
Is there any way to check if array has [null]?
Instead of checking, you may simply filter out all NULL values before other works
if (!isset($request->staff_ids) || $request->staff_ids === null) {
$request->staff_ids = array(); // default to empty array if is not set or is null
}
if (!empty($request->staff_ids)) {
$request->staff_ids = array_filter($request->staff_ids, function ($id) {
return ($id !== null);
});
if (!empty($request->staff_ids)) {
// ...
}
}
I have filtered array values before checking as #KoalaYeung Answered. It is working fine.
$request->staff_ids = array_filter($request->staff_ids, function ($id) {
return ($id !== null);
});
if(isset($request->staff_ids) && !empty($request->staff_ids)){
///
}
Is there any better approach?
you can check this with is_null function and sizeof() for array
if(!is_null($request->staff_ids) && sizeof($request->staff_ids)){
}
Thank you so much for reading and responding if you can.
In one function I test a condition and make a string 'true' or 'false', which then I make a global variable.
Then I call another function with that string as the parameter
Within that function's if statement, I want to test based off the strings boolean value of 'true' or 'false'
$email_form_comments = $_POST['comments']; // pull post data from form
if ($email_form_comments) $comments_status = true; // test if $email_form_comments is instantiated. If so, $comments_status is set to true
else $error = true; // if not, error set to true.
test_another_condition($comments_status); // pass $comments_status value as parameter
function test_another_condition($condition) {
if($condition != 'true') { // I expect $condition to == 'true'parameter
$output = "Your Condition Failed";
return $output;
}
}
My thinking is that $condition will hold a 'true' value, but this is not so.
I think the key here is PHP will evaluate empty strings as false and non-empty strings as true, and when setting and comparing booleans make sure to use constants without quotes. Use true or false not 'true' or 'false'. Also, I suggest writing your if statements so they will set alternate values on a single variable, or in the case of a function return an alternate value when the condition fails.
I made some small modifications to your code so that your function will evaluate true
// simulate post content
$_POST['comments'] = 'foo'; // non-empty string will evaluate true
#$_POST['comments'] = ''; // empty string will evaluate false
$email_form_comments = $_POST['comments']; // pull post data from form
if ($email_form_comments) {
$comments_status = true; // test if $email_form_comments is instantiated. If so, $comments_status is set to true
} else {
$comments_status = false; // if not, error set to true.
}
echo test_another_condition($comments_status); // pass $comments_status value as parameter
function test_another_condition($condition)
{
if ($condition !== true) {
return 'Your Condition Failed';
}
return 'Your Condition Passed';
}
I have this simple function:
function isMember($uID, $pdo) {
$status = getUserStatus($uID, $pdo);
if(isAllowed($status['status']))
return $status['status'];
return false;
}
Now I am looking for a way to return false yes, but to return also the value of the variable.
I tried the following, but it makes it empty anyway:
return $status['status'] == false;
So the logi is return false anyway but give me back also the value of the variable, even if it's false, because false should not mean empty :)
Return an array, and use the list() method to get your results:
function isMember($uID, $pdo) {
$status = getUserStatus($uID, $pdo);
$statusString = $status['status'];
$statusFlag = false;
if(isAllowed($status['status']))
$statusFlag = true;
return array($statusFlag,statusString);
}
//usage
list($flag,$msg) = isMember(5,"whatever");
echo "Access: $flag, with message $msg";
A function can not return multiple values, but similar results can be obtained by (1) returning an array or by (2) passing a variable by reference and storing the value you want returned in that variable.
You will need to write your function in a way that it returns an array containing the following:
The value you wan't returned
A flag that signifies true/false
Pass a variable by reference into your function and store the value of the status in that variable.
function isMember($uID, $pdo, &statByRef) {
$status = getUserStatus($uID, $pdo);
if(isAllowed($status['status'])) {
return $status['status'];
}
$statByRef = $status['status'];
return false;
}
False returns empty in PHP, see http://php.net/manual/en/function.empty.php
From documentation:
Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.
Try using something like this:
function isMember($uID, $pdo) {
$status = getUserStatus($uID, $pdo);
if(isAllowed($status['status'])){
return $status['status'];
}
return false;
} // If isAllowed returns true, then PHP will return $Status['Status'];, if not then PHP will by default return false.
I have noticed you haven't used braces which makes the code a little awkward to debug. Then validate like:
if (isMember($Var,$AnotherVar) !== false){
//isMember has not returned false, so PHP is operating within these braces
}
Such a simple thing, which should be most effective.
If your wanting to assign true/false to $status['status']; then you are performing the right method, but wrong operator.
== is a comparision operator. Not assignment
= is an assignment operator, so your assignment should be:
$status['status'] = false;
I have a function like:
myfunction($i,$condition = false, $level = 0) {
do {
if (... some conditions here) { myfunction($i, true, ++$level) }
else { do something here ... }
while ( ...meet ending condition )
}
I don't understand why the $condition turn true when i call myfunction() recursively and come back to false when iterating in first level and $level won't turn to 0 after it exits a recursive mode.
$condition = false, false, true, false, false, true, true, true ...
$level = 0,0,1,1,1,2,2,2 ... it shoul also be like = 0,0,1,0,0,1,2,2,2,0 ... and so on
?
Thank you
P.S : It is the same with arrays ? I declared an array in the function set to null and when exits the recursive mode it's not null anymore :
myfunction($i,$condition = false, $level = 0, $array = null) {
do {
if($condition) { $array = null } <--------- I HAVE TO ADD THIS LINE TO MAKE IT NULL WHY ?
if (... some conditions here) {$array = Array(someblabla); myfunction($i, true, ++$level, $array) }
else { do something here ... }
while ( ...meet ending condition )
}
What you're missing is the difference between ++$level and $level+1. The former modifies the value of $level, so that further references to that variable in the same invocation of myfunction see the incremented value. If that's not what you want, write $level+1 instead.
Each executed function has its own local variables. As the name says, these variables are local, not shared between recursive calls.
the ++ operator increments the local variable.
This is happening because you are doing ++$level which increments the local copy of $level and then passes the new incremented value to the recursive call of the function.
Try changing it to $level + 1 which just passes value of $value plus one to the function but does not change the local copy of the variable, so that if the function returns you still have the old un-incremented value in $value.
Is this possible? I see some native php functions can do that. For example: strpos() can return 0 which can apparently be true.
Edit
When the manual says some function can return both integer 0 and boolean false, it means it can return either integer 0 or boolean false (not both) in any given call. PHP is not strictly typed, functions can return different types in different situations. For instance, the following function returns either 0 or false, depending on whether the passed parameter is non negative or not:
function myfunc($arg) {
if ($arg >= 0)
return 0;
else
return false;
}
Original
PHP has no multiple return. You have two options:
Return composite values instead
function myfunc() {
return array(0, true); //return array
}
class MyOutputHolder {
private $number;
private $truth;
function getNumber { return $this->number; }
function getTruth { return $this->truth; }
function __construct($number, $truth) {
$this->number = $number;
$this->truth = $truth;
}
}
function myfunc() {
return new MyOutputHolder(0, true); //return object
}
A third possibility is a custom resource, but that must be implemented internally (in an extension).
Use output parameters
function myfunc(&$outnumber, &$outtruth) {
$outnumber = 0;
$outtruth = true;
}
Of course, you can return only 0 or true and use only one parameter.
For functions that can return successfully with the return value of zero, you should be using type equivalence checking.
if(somefunction() !== false) {
}
The integer zero is interpreted as false if type is not considered. For example, assuming somefunction returns zero.
somefunction() != false
Will be false, while
somefunction() !== false
Will be true.
Your confusion is that strpos returns the zero-based index of the search string.
So in this case, 0 is a valid return, it means "found it at index 0"
If the string isn't found at all, then it returns FALSE.
It's important to note what's written in big red warning in the strpos doc page:
This function may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please read
the section on Booleans for more
information. Use the === operator for
testing the return value of this
function.
ie: 0 is not exactly FALSE in php. It's fundamental of php. 0 == FALSE but 0 !== FALSE
As too why PHP can return either a numeric value or a boolean - maybe that's your actual question - PHP isn't strongly typed, you never specify what you'll be returning, so you're free to return different data types depending on the outcome of the function
Does this count?
function stupid() {
return "0\0";
};
echo stupid() ."\n";
var_dump(stupid());
if (stupid()) echo "true\n";
echo stupid() + 4 . "\n";
Output:
0
string(2) "0"
true
4
*ducks*
A function can only ever have one return value. However, you can return an array with multiple values if you need to.
I think you're misunderstanding what strpos actually returns...
strpos() returns either an integer greater than or equal to zero, or it returns false (if the needle character is not found in the string).
0 does not equal true in any sense - what the PHP documentation does mention, though, is that because of PHP's loose-typing, 0 can equal false unless you use the conditional operator that forces type as well as value comparison.
var_dump(0 == false); // 'true'
var_dump(0 == true); // 'false'
var_dump(0 === false); // 'false'
var_dump(0 === true); // 'false'
var_dump(0 !== false); // 'true'
this is why the PHP manual recommends you test the return value from strpos() with '!== false' because the character you are searching for may be the first character in the string and therefore the function returns 0.
$string = "_testing";
var_dump(strpos($string, '_')); // 0
var_dump(strpos($string, '_') !== false); // 'true'
var_dump(strpos($string, '_') === true); // 'false'
return 0 && true;