romain.pelissier Posted June 15, 2007 Share Posted June 15, 2007 Hi, This is my very first post here and also my very first php code. I hope that someone could help me. I would like to create the condition of the 'if' function on the fly, meaning : $condition="$a > $b"; // this variable is a string that contain the 'if' condition .... $a=1; $b=1; if ($condition) { ... } I hope you see what I mean here... In fact, I try to build the condition of the 'if' function so at the end it 'virtually' looks like this: if ($a > $b){ ... } Of course, here that does not work because $a=$b. I have already posted on some french php forum http://www.phpfrance.com/forums/voir_reponse-198405.php#198405 (by the way, I french) but I don't have the answer yet. They pointed me with several options but in my case, that does not solve my issue. Why? Simply because It is a little more complex that the example I gave above. So, let me be a little more specific on my code and what I want : (please, don't tell me my code is ungly, I already know that : I am not a professional programmer and this is my first attemtp to use php ... ) function getFiles($path) { //Function takes a path, and returns a numerically indexed array of associative arrays containing file information, //sorted by the file name (case insensitive). If two files are identical when compared without case, they will sort //relative to each other in the order presented by readdir() $files = array(); $fileNames = array(); $i = 0; if (is_dir($path)) { if ($dh = opendir($path)) { while (($file = readdir($dh)) !== false) { if ($file == "." || $file == "..") continue; $fullpath = $path . "/" . $file; $fkey = strtolower($file); while (array_key_exists($fkey,$fileNames)) $fkey .= " "; $a = stat($fullpath); $files[$fkey]['size'] = $a['size']; if ($a['size'] == 0) $files[$fkey]['sizetext'] = "-"; else if ($a['size'] > 1024) $files[$fkey]['sizetext'] = (ceil($a['size']/1024*100)/100) . " K"; else if ($a['size'] > 1024*1024) $files[$fkey]['sizetext'] = (ceil($a['size']/(1024*1024)*100)/100) . " Mb"; else $files[$fkey]['sizetext'] = $a['size'] . " bytes"; $files[$fkey]['name'] = $file; $files[$fkey]['type'] = filetype($fullpath); $t = extractdateinfo($file); $dat1 = $t[0]; $files[$fkey]['datedebut'] = substr($dat1, 0,strpos($dat1, "-")); $files[$fkey]['datefin'] = substr($dat1, strrpos($dat1, "-") + 1); // insertion de la cle pour la date de modification du fichier $files[$fkey]['datemodif'] = date("Ymd", filemtime($fullpath)); $fileNames[$i++] = $fkey; } closedir($dh); } else die ("Cannot open directory: $path"); } else die ("Path is not a directory: $path"); sort($fileNames,SORT_STRING); $sortedFiles = array(); $i = 0; foreach($fileNames as $f) $sortedFiles[$i++] = $files[$f]; return $sortedFiles; } function mainmanage($tabfiles,$criteria1,$rule1) { $patern1='['.$criteria1.']'; $patern2='['.$criteria2.']'; $r=0; $o=0; $tab01=array(); $tab02=array(); foreach ($tabfiles as $fi) { $ext = substr($fi['name'], strrpos($fi['name'], '.') + 1); if ( $ext == "xls" ) { if (preg_match($patern1, $fi['name'])) { $is_date=date("Ymd"); $debut = substr($fi['datedebut'],0, 6); $fin = substr($fi['datefin'], 0, 6); $dateactu = substr($is_date, 0, 6); //$dateactu = substr($dd1, 0, 6); print "</br>\n"; print "fin = ".$fin; print "</br>\n"; print "actu =".$dateactu; print "</br>\n"; print "condition = ".$rule1; print "</br>\n"; if ($rule1) { $lm = date("F d Y H:i:s.", filemtime($fi['name'])); $year = substr($fi['datemodif'], 0, 4); $month = substr($fi['datemodif'], 4, 2); $day = substr($fi['datemodif'], 6, 2); $formateddate = date("l, dS F, Y", mktime(0, 0, 0, $month, $day, $year)); $d1 = substr($fi['datedebut'],0 , 4) . "-" . substr($fi['datedebut'], 4, 2) . "-" . substr($fi['datedebut'], 6, 2); $d2 = substr($fi['datefin'],0 , 4) . "-" . substr($fi['datefin'], 4, 2) . "-" . substr($fi['datefin'], 6, 2); $str=" <b><a style=\"font-family:verdana\"> Du $d1 au $d2 : </a><a style=\"font-family:verdana\" href=\"$fi[name]\">[xls]</a></b><br>\n"; $v=strval($r); $tab01[$v]['datedebut']=$fi['datedebut']; $tab01[$v]['datefin']=$fi['datefin']; $tab01[$v]['str']=$str; $r++; } } } } return array( $tab01); } $path = $folder_path; $files = getFiles($path."/"); $fresult=mainmanage ($files, "Horaire_Analyste", '($dateactu >= $debut) && ($dateactu < $fin)'); The getFiles function return from a given path an array that contain all files in a folder The mainmanage function should allow me that from this array to check a couple of things: - check if the file extension is xls - check if the current file name (from the array that I am looping in) match a preg_match patern - check, after a file manipulation where I extract some date infos, if the current date is between an interval of date (from the file name string manipulation). If the test is successfull then the result are inserted in an array This array will be used later to display the results on the page. The file format should looks like : yadayada_yyyymmdd-yyyymmdd.xls As you can see, I have tried to give as a paramter the condition of the 'if' function but in this example that does not work I would like to use a 'generic' function to handle that. I call this function several time in the page and only few parameters change from one call to the other : the array of file name, the patern for the preg_match and the 'if' condition. Then I use the resulting array to display the result. I have done several tests ... If I send as a parameter for the 'if' function condition '($dateactu >= $debut) && ($dateactu < $fin)' ou '('.$dateactu.' >= '.$debut.') && ('.$dateactu.' < '.$fin.')' the result within the function is alway the same : ( >= ) && ( < ). If I put the try this condition inside the function (as a test string) as this : '('.$dateactu.' >= '.$debut.') && ('.$dateactu.' < '.$fin.')' then in this case the variables are correctly interpreted and the result is (200706 >= 200706) && (200706 < 200709). So it seems that the variables in my condition parameter are eveluated to NULL et never been updated even after $debut, $fin and $dateactu are set correcty in the function... I don't know if this is even possible, I only try to find the correct answer to this issue. Maybe they are some ways to solve this problem in other way, in this case, juste let me know what do you think that could solve my problem. Sorry again for my english ... Quote Link to comment https://forums.phpfreaks.com/topic/55740-need-help-building-an-if-condition-on-the-fly/ Share on other sites More sharing options...
per1os Posted June 15, 2007 Share Posted June 15, 2007 Literal values are taken literally. That is why checking against a $rule even it has say "4 < 1" will always return true. Why? Because $rule1 technically returns a number > 1 which in return is interpreted as "true". If $rule was empty or null it would return false. You may be able to use www.php.net/eval to do this, but highly doubtful. The only way to really do this is build a complex function that parses out the data and then regenrates it: <?php function condition_run($condition_str) { $and_portion = explode("&&", $condition_str); if (count($and_portion > 0)) { $condition_true = true; foreach ($and_portion as $and) { $rest = explode(" ", $and); if (!condition_test($rest[0], $rest[2], $rest[1])) { $condition_true = false; break; } } return $condition_true; } return false; } function condition_test($val1, $val2, $condition) { switch ($condition) { case '<': if ($val1 < $val2) { return true; } break; case '>': if ($val1 > $val2) { return true; } break; } return false; } ?> Keep in mind I kept that very simple. It could be alot more dynamic and complex, but hopefully that gets you the idea. Quote Link to comment https://forums.phpfreaks.com/topic/55740-need-help-building-an-if-condition-on-the-fly/#findComment-275405 Share on other sites More sharing options...
romain.pelissier Posted June 15, 2007 Author Share Posted June 15, 2007 I was pretty sure that I couldn't make it using a simple magic string manipulation but thank you very much for your code! It seems to fit my needs. I will test it and let you know about the result. I will let this topic unsolved until I have some other replies from other forum. I will post here in few days the other options if there are some. Thanks again for your help frost110. Quote Link to comment https://forums.phpfreaks.com/topic/55740-need-help-building-an-if-condition-on-the-fly/#findComment-275413 Share on other sites More sharing options...
romain.pelissier Posted June 15, 2007 Author Share Posted June 15, 2007 Still got a problem ... It seems to work perfectly but I have an issue with variables ... Here is my test : function condition_run($condition_str) { print "condition = ".$condition_str; $and_portion = explode("&&", $condition_str); if (count($and_portion > 0)) { $condition_true = true; foreach ($and_portion as $and) { $rest = explode(" ", $and); if (!condition_test($rest[0], $rest[2], $rest[1])) { $condition_true = false; break; } } return $condition_true; } return false; } function condition_test($val1, $val2, $condition) { switch ($condition) { case '<': if ($val1 < $val2) { return true; } break; case '>': if ($val1 > $val2) { return true; } break; case '>=': if ($val1 >= $val2) { return true; } break; case '<=': if ($val1 <= $val2) { return true; } break; case '=': if ($val1 = $val2) { return true; } break; } return false; } //$a=1; //$b=2; $cond="$a > $b"; test_function($cond); function test_function($rule){ $a=1; $b=2; condition_run($rule); } This is as close as possible to what I want to acheive meaning : - I call a function with the condition string as parameter - In this function, I set $a and $b to their values - I call the condition_run function with the condition parameter but the result if that $a and $b seems NULL or empty ... Any idea? Quote Link to comment https://forums.phpfreaks.com/topic/55740-need-help-building-an-if-condition-on-the-fly/#findComment-275469 Share on other sites More sharing options...
per1os Posted June 15, 2007 Share Posted June 15, 2007 Well for starters this case '=': if ($val1 = $val2) { return true; } break; should be case '==': if ($val1 == $val2) { return true; } break; as for why $a and $b are null or empty, I do not think it has anything to do with the functions above. Do some debugging and see why they are not being set. Quote Link to comment https://forums.phpfreaks.com/topic/55740-need-help-building-an-if-condition-on-the-fly/#findComment-275488 Share on other sites More sharing options...
romain.pelissier Posted June 18, 2007 Author Share Posted June 18, 2007 Thanks for you answer frost110. It seems that there is no easy way to acheive what I want. Anyway I have use several tips found here to solve (kind of) my problem. But, buildind a condition before settings the value seems to possible if you have PHP5. Look at the execellent code of Wierdan at http://forums.devnetwork.net/viewtopic.php?p=391399#391399. I cannot test it right now, but feel free to test it and add some comments here. Quote Link to comment https://forums.phpfreaks.com/topic/55740-need-help-building-an-if-condition-on-the-fly/#findComment-276843 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.