Change if condition dynamically - php

I'd like to dynamically change a condition, depending on whether or not a table is empty.
If the table is empty, it should record all data up to yesterday, if not empty, it should record today's data.
My current code is not working:
$db->get('history');
$emptyTable = $db->count; // This return 0 or 1
$condition = setCondition($emptyTable);
foreach($extract as $trade) {
$date = strtotime($trade['Date']);
$today = strtotime(date("d/m/Y"));
if($condition) {
// do something
}
}
function setCondition($bool) {
switch ($bool) {
case 1:
return $date == $today;
break;
case 0:
return $date < $today;
break;
}
}

You are not passing $date and $today to your function and call it inside foreach and enclose the return part in setCondition so that it will return the string ..
foreach($extract as $trade) {
$date = strtotime($trade['Date']);
$today = strtotime(date("d/m/Y"));
$condition = setCondition($emptyTable,$today,$date);
// echo $condition//condition string
if($condition) {
// do something
}
}
function setCondition($bool,$today,$date) {
switch ($bool) {
case 1:
return "'$date' == '$today'";
break;
case 0:
return "'$date' < '$today'";
break;
}
}
DEMO

Your condition itself needs to be a call to a function returning a boolean value. This is what your setCondition function does:
function setCondition($bool) {
switch ($bool) {
case 1:
return $date == $today;
break;
case 0:
return $date < $today;
break;
}
}
Since it does not set anything, I suggest you rename it evaluateCondition.
Henceforth, you can directly call this function as a condition:
if(evaluateCondition($booleanVariableToTest)) {
// do something
}
Regarding why your code does not work: you basically evaluate $condition once, at the beginning:
$condition = setCondition($emptyTable);
After that, $condition never changes. Therefore, it is not dynamically re-evaluated.
Edit
From reading a comment of you, I understand that you're not actually trying to dynamically evaluate a condition, but statically evaluate it, depending on other parameters (namely, $date and $today).
Your function needs to take these variables as arguments, so their names actually mean something in the scope of this function. The right code is:
function setCondition($bool, $date, $today) {
switch ($bool) {
case 1:
return $date == $today;
break;
case 0:
return $date < $today;
break;
}
}
In this case, you do not need to call the setCondition function at every iteration, so your if test remains:
if($condition) {
// do something
}

Related

switch loop doesnt recognize zero "0" php

I have this simple function to convert the number of comments of an user to types of members.
function checkMemberN($numMessages){
$n= $numMessages;
switch ($n) {
case ($n<50): $type="New"; break;
case ($n>=50 && $n<250):$type="Frequent";break;
case ($n>=250 && $n<1000): $type="Master";break;
default: $type="undefinded";
}
return $type;
}
echo checkMemberN(0);
It looks like it doesn't recognize zero (0), because when I put 1 or a higher number it retrieves the correct user type. What am I doing wrong?
When you use switch, the first case which returns a value equal to the given one is selected. In this case, your argument (zero) is a false-y value. That's why the first case that returns false is chosen: "Frequent".
To fix it, you can do this:
if ($n<50) {
$type = "New";
} else if ($n>=50 && $n<250) {
$type = "Frequent";
} else if ($n>=250 && $n<1000) {
$type = "Master";
} else {
$type = "undefined";
}
If you still want to use switch, you can change the argument to true:
switch (true) {
case ($n<50): $type="New"; break;
case ($n>=50 && $n<250):$type="Frequent";break;
case ($n>=250 && $n<1000): $type="Master";break;
default: $type="undefinded";
}
Here, the first case which returns true will be used.

Is there any possibility to break a loop while calling a function?

Let's say I have a simple code:
while(1) {
myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) break;
}
This will not work with error code 'Fatal error: Cannot break/continue 1 level on line'.
So is there any possibility to terminate the loop during a subfunctin execution?
Make the loop condition depend upon the return value of the function:
$continue = true;
while( $continue) {
$continue = myend();
}
Then, change your function to be something like:
function myend() {
echo rand(0,10);
echo "<br>";
return (rand(0,10) < 3) ? false : true;
}
There isn't. Not should there be; if your function is called somewhere where you're not in a loop, your code will stop dead. In the example above, your calling code should check the return of the function and then decide whether to stop looping itself. For example:
while(1) {
if (myend())
break;
}
function myend() {
echo rand(0,10);
echo "<br>";
return rand(0,10) < 3;
}
Use:
$cond = true;
while($cond) {
$cond = myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) return false;
}

Using variables in if statements

PHP novice here. I searched for this, but i'm sure i'm not using the right syntax regarding my issue. Apologies then if this is a duplicate:
I have these 3 variables:
$param = get_sub_field('custom_parameter');
$compare = get_sub_field('parameter_compare');
$param_val = get_sub_field('parameter_value');
each one would return this:
$param is 'my_parameter'
$compare is either '==', '<=', or '=>'
$param_val is something like '5' or any value that the user sets
What i have is an editing interface where the user can set their parameter name, set the compare and then add the value. To that they can also add an action that occurs if the parameter matches. I'm using this in conjunction with $_GET.
What i'd like to do is insert each variable from above into my if statement so the comparison is created by the user. However, it keeps giving me an error when i try to do this:
if($_GET[$param] $compare $param_val) {
// do something
}
The error i get is:
Parse error: syntax error, unexpected T_VARIABLE
This of course works just fine:
if($_GET[$param] == $param_val) {
// do something
}
Hopefully i've explained this well enough and any help is greatly appreciated.
Update: Thank you for answering this for me and jumping on it so quickly. Learned a ton here!!
function comparer($param, $compare, $param_val)
{
switch ($compare){
case '==': return $param == $param_val;
case '!=': return $param != $param_val;
case '<=': return $param <= $param_val;
case '>=': return $param >= $param_val;
case '<': return $param < $param_val;
case '>': return $param > $param_val;
default: return FALSE;
}
}
/* ... */
if (comparer($param, $compare, $param_val)){
// true
}
Very simple method to get you going. I would, at all costs, resist the temptation to use eval, unless you want to invest a lot of time in sanitizing those three parameters.
Oh, and an example
I think I would use a switch statement to avoid any scary eval code.
Such as:
switch($compare) {
case '==':
if($_GET[$param] == $param_val) {
// do something
}
break;
case '<=':
if($_GET[$param] <= $param_val) {
// do something
}
break;
case '>=':
if($_GET[$param] <= $param_val) {
// do something
}
break;
}
Look at eval()
http://php.net/manual/en/function.eval.php
With this you can parse a code you format in a string.
The best way would be to make a function for this. Have that function uses a switch to determine the operator, then return the comparison.
function compare($a, $b, $operator){
$ret = NULL;
switch($operator){
case '==':
$ret = $a == $b;
break;
case '>=':
$ret = $a >= $b;
break;
case '<=':
$ret = $a <= $b;
break;
}
return $ret
}
Then just simply call it:
if(compare($_GET[$param], $param_val, $compare)){
// do something
}
Hmm interesting, I think I'd approach it like this (untested):
function comparison($param, $compare, $param_val) {
if ($compare == '==') {
if ($param == $param_val) {
return true
}
}
if ($compare == '<=') {
if ($param <= $param_val) {
return true
}
}
if ($compare == '>=') {
if ($param >= $param_val) {
return true
}
}
}
Not very efficient or DRY, could probably use a switch as that would probably be better but this was the first thing to pop into my head.
Usage
if (comparison($param, $compare, $param_val)) {
echo 'it's true';
} else {
echo 'it's false';
}
Edit
As per usual, I have been beaten to the punch by better code :)
P.S. I'm not sure why you have $param and then use $_GET[$param] so I've just used $param in my answer.

Using conditional values from an array in an if...statement

I have an array of conditions :
$arrConditions = array ('>=2', '==1', '<=10');
...which I want to be able to use in an if...statement.
IE.
if (5 $arrConditions[0])
{
...do something
}
...which would be the same as :
if (5 >= 2)
{
...do something
}
Any help?
Thanks
Such a requirement is a sure sign of a bad design.
Most likely you can do that another, more usual way.
Nevertheless, never use eval for such things.
At least store each operator in pairs - an operator and operand.
$arrConditions = array (
array('>=',2),
array('==',1),
array('<=',10),
);
and then use switch:
list ($operator,$operand) = $arrConditions[0];
switch($operator) {
case '==':
$result = ($input == $operand);
break;
case '>=':
$result = ($input >= $operand);
break;
// and so on
}
But again - most likely you can solve it another, much easier way.
What about this ?
<?php
$arrConditions = array('==2', '==9', '==5', '==1', '==10', '==6', '==7');
$count = 0;
$myval = 0;
foreach ($arrConditions as $cond) {
$str = "if(5 $cond) { return $count;}";
$evalval = eval($str);
if (!empty($evalval)) {
$myval = $count;
}
$count++;
}
switch ($myval) {
case 0: echo '==2 satisfied';
break;
case 1: echo '==9 satisfied';
break;
case 2: echo '==5 satisfied';
break;
case 3: echo '==1 satisfied';
break;
case 4: echo '==10 satisfied';
break;
default : echo 'No condition satisfied';
}
?>

Use of switch and case in php and codeigniter

I want use of switch and case in php and codeigniter library, i try it as following code, But I not receive output. what do i do?
Demo: http://codepad.viper-7.com/Wq0Noj
function indicators() {
$CI = &get_instance();
$Year = '1355';
$Month = '03';
switch ($Year) {
case 1354:
$key=array('0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6');
$output = $key[$Month-1];
break;
case 1355:
$key=array('0.6','0.7','0.2','0.4','0.7','0.1','0.7','0.2','0.5','0.9','0.4','0.8');
$output = $key[$Month-1];
break;
echo $output; // The output should be: 0.7
}
}
I think your echo needs to be outside of the switch as well... checking to verify.
Yep, the echo needs to be outside. The type should actually be coerced when comparing.
<?php
$s = '5';
switch ($s) {
case 5:
echo "Foo\n";
break;
default:
echo "Bar\n";
break;
}
echo $s;
OUTPUT
Foo
5
And for your example:
<?php
function indicators() {
$Year = '1355';
$Month = '03';
switch ($Year) {
case 1354:
$key=array('0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6','0.6');
$output = $key[$Month-1];
break;
case 1355:
$key=array('0.6','0.7','0.2','0.4','0.7','0.1','0.7','0.2','0.5','0.9','0.4','0.8');
$output = $key[$Month-1];
break;
}
echo $output; // The output should be: 0.7
}
indicators();
OUTPUT
0.2
Which is correct according to the code. '03' - 1 == 2. $key[2] == '0.2'
As pointed out in the comment below by #vstm, the docs state that the "switch/case does loose comparision."

Categories