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.
Related
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).
Why does this code work correctly?
function isLoggedIn(){
return false; //or true
}
if($user = isLoggedIn())
{
echo "Hello ".$user['name']; //if isLoggedIn returns true, this prints
} else {
echo "Please login to proceed!";//if isLoggedIn returns false, this prints
}
I always thought assignment operator inside an if() condition will always evaluate to true since it is only evaluating whether the value of right hand side can be assigned to left hand side...
It's evaluating the value of $user after assigning the return of isLoggedIn() to $user. It's the same as:
$user = isLoggedIn();
if($user) {}
It's especially handy in loops:
while($var = someFunction()) {
//do stuff with $var
}
And more expressions:
if($var = someFunction() && $var !== 'bad') {}
if($var = someFunction() && $var === 'good') {}
In PHP, an assignment operation actually has a return value, and it's the value that was assigned. Your if() condition works for the exact same reason that
$x = $y = $z = 42;
works. This statement will assign the value 42 to all three variables, and is functionally the equivalent of
$z = 42;
$y = $z;
$x = $y;
In your case, your isLoggedIn() function call will execute and return a value. That value assigned to $user. Then that value is "returned" to the if() statement itself and is used for the logic test.
If your function had returned boolean false, or a "falsey" value, then the "else" clause would have executed. e.g.
function returns_false() {
return false;
}
if ($foo = returns_false()) {
echo 'if was true';
} else {
echo 'if was false'; // this line will get executed
}
Even though the assignment operation succeeded, it's the value that got assigned that matters, not the success/failure of the operation. so the "it was false" code path gets executed, because the function call returned a false, which propagated up the decision tree.
The condition considers $user after assignment.
Therefore it will be true or false depending on the value returned by isLoggedIn()
There is one note. Code like this will not work as expected:
if($var = someFunction() && $var !== 'bad') {}
if($var = someFunction() && $var === 'good') {}
Because $var will contain not a value returned by someFunction(), but a boolean value of the whole expression, like this:
$var = (someFunction() && $var !== 'bad');
if($var) {}
To get the result you need you should use brackets:
if(($var = someFunction()) && $var !== 'bad') {}
if(($var = someFunction()) && $var === 'good') {}
You can find details on the php.net website.
It works because the IF is TRUE. Oddly enough it will always be TRUE. Because you are assigning the value when you only use one = sign. If you want to check the contents, you have to use ==.
As everyone has already suggested, there are two parts to the statement:
It assigns the value of isLoggedIn() to $user.
It then returns the same value to whichever construct asked for it. In this case, it's
returned to the if () statement.
It is worth noting that although the if () statement expects to receive a boolean value true or false. If the if () receives a value that isn't a boolean, it is still acceptable in PHP (as well as JavaScript). If any operator or statement receives a value of the wrong type, PHP will convert it to boolean=true in most cases.
I have a Callback function, that, the second parameter is an Array.
So, I have something like:
public function foo ($something, $callback) {
/**
* function body
*/
$booleanOrArray = $this->bar();
if ( is_callable ( $callback ) ) {
return call_user_func ( $callback, !is_array($booleanOrArray), $booleanOrArray || [ ]);
}
throw new Exception('A callback function must be defined.');
}
So, in the call_user_func, there's a var that is called $booleanOrArray. This is because, if the procces of the function bar is well done, then, returns an Array with data, otherwise, the bar function returns false; so, if bar returns false, the first parameter in the callback function is determined by is_array($booleanOrArray), so, if foo returns false, there is an error, and, if is an Array, this param will be false.
But, in my app, I force to the user to define the callback function as follows:
$MyClass = new ClassInstance();
$MyClass->foo('firstParam', function ( $error, Array $data ) {
if ( ! $error ) {
var_dump($data);
}
else {
print 'Hey!';
}
});
But, after all these code, I was surprised to realize that $booleanOrArray || [ ] always returns false.
In Javascript, if I code var x = foo || bar;, if foo is null, or false, or undefined, then x will have the bar value, and vice versa.
So, the question:
Is this possible in php, or I have to do something like $x = ($booleanOrArray) ? $booleanOrArray : [ ] ?
Do you have any idea to improve the callback function in this case? (not opinion based, only standards)
something like $x = ($booleanOrArray) ? $booleanOrArray : [ ] ?.
Yes, you can even use shortened ternary syntax:
$booleanOrArray ?: []
This results in $booleanOrArray if it is not falsy or empty array otherwise.
I am passing the two var's by ref to change them, and once I have changed them or one of the (8 loops) have found a positive in the string I am using, I want to exit the function, but I don't need to return anything because they are passed by ref.
I could just pass a copy of one and then ref the other one and set the var of the one that is copied = to the function and return that, but is there a cleaner way where I just call the function, the vars are set and I can move on?
function get_cat_size($urlstr, &$cat, &$size){ return null; };
$cat = get_cat_size($urlstr, &$size);
Does the first one work or not? Witch is better for readability?
Thanks for the input!
while( $i < $countz )
{
$pos = strpos($outdoor, $outdoor[$i]);
if($pos != false)
{
$cat = $outdoorID;
while( $j < $sizeArrayCount)
{
$poz = strpos($outdoor, $outdoor[$i]);
if($poz != false)
{
$size = $outdoorID;
return;
}
$j++;
}
return;
}
$i++;
}
^ so this should work yes no maybe so?
So this is one of 8 loops set up in a order because they are least important to important, with different var = different stores.
You can just return without a value:
function returnsNothing (&$a, &$b) {
return;
}
Or simpler just omit the return statement at all
function returnsNothing (&$a, &$b) {
// do something
}
Both snippets will make the function returning NULL.
Take a look at break for returning out of your for loops.
I would personally avoid returning null within a function since NULL will be returned by default when there is no return value specified. You can read more here at PHP: Returning values
check::empty_user()
below will test an array for 'empty' values -
NULL, FALSE, 0, or ' '
/*check*/
class check
{
static function empty_user($a)
{
return (int)!in_array('',$a);
}
}
function test_empty(array $array) {
foreach($array as $elem) {
if (!empty($elem)) return false;
}
return true; // no element, or no non-empty element
}
in_array('', $array);
I think that is what you're after?
Your function isn't going to test anything other than the first element of your array. Return causes the function to cease execution.
PHP has empty and isset functions, either of those should be suitable testing array elements. To test the entire array you can use in_array and look for empty values. However you'll have to implement your own method for processing nested arrays.
You test empty could also be the folowing:
// if the array has at least one empty value
function test_empty(array $array) {
foreach($array as $elem) {
if (empty($elem)) return true;
}
return false;
}
In summary use
empty() or in_array()
and make note that:
$value=='' tests for null, false, 0, and ''