0

I'd like my function to have a comparison operator as an argument (or preferably, as part of an argument such as >0 ):

Instead of

function comps($a,$b){
    if ($a > $b)
      echo "This works.";
}
comps(1,0);

I'd like to be able to do something like

function comps($a,$b){
    if ($a $b)
      echo "This works.";
}
comps(1,'>0');

I've been banging my head agains the wall on this for a while. I've tried different iterations of:

"/>0"
'>' . 0
(string)> 0

as well as trying the comparison operator as a third argument.

Actual use is:

function mysort($key,$match){
$temp_array = array();
global $students;

foreach ($students as $row) {
    if($row[$key] > $match ) 
    $temp_array[]= $row;
    }

foreach ($temp_array as $row) {
    echo $row['email'] . ', ';
    }
}
mysort('suzuki', '0'); 

Thanks

Kale
  • 55
  • 1
  • 8
  • 1
    1) Use a third parameter for the operator 2) Use a switch statement to determine which code with which operator needs to be executed. – Rizier123 Aug 14 '16 at 18:39
  • Possible duplicate of [Dynamic Comparison Operators in PHP](http://stackoverflow.com/questions/2919190/dynamic-comparison-operators-in-php) – Charlotte Dunois Aug 14 '16 at 18:45
  • not sure if I need to do those two in conjunction, but I certainly tried step 1. I'll add that to be clear. – Kale Aug 14 '16 at 18:45
  • Somewhat duplicate, but I don't need the dynamic part. Not sure how to break that solution down (or if it will even work for me), but I'll start checking it out. – Kale Aug 14 '16 at 18:56

2 Answers2

0

You can make a return type function and use as you want.

I'll Make a function to you as Below:

<?php
    function getCond($a, $b, $both) {
        $data = false;
        if($both) {
            if($a == b) {
                $data = true;
            }
        }else {
             if($a > $b) {
                 $data = true;
             }
        }
        return $data;
    }

 /*  Use Your Function  */
    if (getCond(10, 5, true)) {      // condition for 10 == 5 and according to passed values you get false result in condition 
        echo "you result";
    } else if (getCond(10, 5, false)) {  // condition for 10 > 5 and according to passed values you get false result in condition
        echo "your result";
    } else if (getCond(6, 5, false)){    // condition for 6 > 5 and according to passed values you get true result in condition
        echo "your result";
    } 
?>

You also can modify this function as you want :)

Rajpal Singh
  • 307
  • 1
  • 12
0

The simplest solution for my use seems to be:

function comps($a,$b,$c){
if ($a > $b  and $a < $c)
echo "True";
}

comps(1,0,2);
?>
Kale
  • 55
  • 1
  • 8