Solved

Condition is Array  (PHP)

Posted on 2013-07-01
15
368 Views
Last Modified: 2013-07-06
Dear Experts,
If my PHP coding as follow :
// it is working
if (($z>8.5) AND ($z<=9))
----
But if my coding as follow :
// But if using array the logical operation is not working
$fformula[1]="(($z>8.5) AND ($z<=9))";
if ($fformula[1])

The attachment is the complete coding

What Shoud I do ?

Thanks
niken

++++++++++++

<?php
// input
$z = 100;
//$z = 8.6;
//formula
$fformula[1]="(($z>8.5) AND ($z<=9))";
$fformula[2] ="(($z>9) AND ($z<=11))";
//result
$fresult[1] = 9 ;
$fresult[2]= 6 ;
// just test to echo formula
echo "$fformula[1]";
echo "<br />";
echo "$fformula[2]";
echo "<br />";
//just test to echo fresult
echo "$fresult[1]";
echo "<br />";
echo "$fresult[2]";
echo "<br />";

// If like this, it's work
//if (($z>8.5) AND ($z<=9))
// But if using array the logical operation is not working
if ($fformula[1])
      {
      $result = $fresult[1];      
       echo " The result is = $result";
      }
//elseif (($z>9) AND ($z<=11))      
elseif ($fformula[2])
   {
   $result = $fresult[2];      
       echo " The result is = $result";
      }
else
 {
 echo "wrong formula";
      }
 
  echo "<br />";
?>
simba6.php
0
Comment
Question by:niken_asterina
  • 5
  • 4
  • 2
  • +3
15 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39291907
Why are you converting the code to a string?

i.e.

$fformula[1]="(($z>8.5) AND ($z<=9))";
0
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 39291913
It simply does not work that way.  You can not substitute an array or even a string variable for the conditions in an 'if' statement.  You have to write them out explicitly like the working versions you show.
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39291919
Please tell us in plain language what you want to accomplish and show us the input data.  We do not need to see programming that doesn't work -- we have written a lot of that in our lifetimes!  It's all about the test data.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_7830-A-Quick-Tour-of-Test-Driven-Development.html
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 82

Expert Comment

by:hielo
ID: 39291989
try removing the double quotes - it should evaluate the expression:
...
$fformula[1]=(($z>8.5) AND ($z<=9));
$fformula[2] =(($z>9) AND ($z<=11));
...
if( $fformula[1] )
{
 ...
}

Open in new window

0
 
LVL 23

Accepted Solution

by:
Mysidia earned 400 total points
ID: 39292000
Let's back up a bit:

WHY  are you trying to place a logical string inside an expression?


You cannot  execute  PHP  code inside a string,  without an eval()  enclosure,  or without parsing it.     You run the risk of security vulnerabilities,  without extreme caution in the use of eval(),  and code injection is definitely not a good programming practice.


You could technically build an anonymous expression from your string
as in

if ( eval('return ' .  $fformula[1] . ';') )  {
   ....
}


or

$ffunction = array();

for ($fformula as $k => $v) {
   $ffunction[$k] =  function($z)  { global $fformula; return eval('return ' .  $fformula[$k] ) };
}
...

if ($ffunction[0]($z)) {
  ...
}




But the  'if (($z>8.5) AND ($z<=9))'
form is what would generally be used in a real PHP program
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39292006
0
 
LVL 1

Author Comment

by:niken_asterina
ID: 39298640
Dear Experts,
What I want to do to retrieve a logical operation formula from existing application database.
In the one column consist a formula such as :
f(9)=((@>8.5) AND (@<=9));
f(6)=((@>9) AND (@<=11));
f(1)=((@>11) AND (@>=15));

If the formula like that, it means I get 9 if the input is 8.6, I get 6 if the input is 10 and I get
1 if the input is 13. (This is my goal)

I have parsed the data using  :

$normalichange1 = str_replace("@", "$z", $normali);
$normalichange = str_replace(")=", ";", $normalichange1);
$fformula = preg_split ("/[;]/", $normalichange);

for ($i = 0; $i < count($fformula); $i+=2) {
            $fformula1[$i] = str_replace("f(", "", "$fformula[$i]");
        print "$fformula1[$i] <br />";
    }
for ($j = 1; $j < count($fformula); $j+=2) {
        print "$fformula[$j] <br />";
    }

But the problem when I should put the formula into If condition, it cannot works
I couldn't change the database because it is used by existing application.
____
The complete coding as follow

<?php

$normali= "
f(9)=((@>8.5) AND (@<=9));
f(6)=((@>9) AND (@<=11));
f(1)=((@>11) AND (@>=15));";

//$z = 8.6;
$z = 100;
$normalichange1 = str_replace("@", "$z", $normali);
$normalichange = str_replace(")=", ";", $normalichange1);
$fformula = preg_split ("/[;]/", $normalichange);
echo "<br />";

for ($i = 0; $i < count($fformula); $i+=2) {
            $fformula1[$i] = str_replace("f(", "", "$fformula[$i]");
        print "$fformula1[$i] <br />";
    }
echo "<br />";

echo "<br />";

for ($j = 1; $j < count($fformula); $j+=2) {
        print "$fformula[$j] <br />";
    }
echo "<br />";


if (($fformula[1]))
      {
      $result = $fformula1[0];      
       echo " The result is = $result";
      }
      //elseif (($z>9) AND ($z<=11))      
elseif ($fformula[3])
   {
   $result = $fformula1[2];      
       echo " The result is = $result";
      }
elseif ($fformula[5])
   {
   $result = $fformula1[4];      
       echo " The result is = $result";
      }

else
 {
 echo "wrong formula";
      }
 
  echo "<br />";
 
  echo "<br />";
?>
0
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 39298682
That doesn't make a bit of sense to me.  What is in the database?  What are you looking for?
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39298800
Please do not post any code that does not work.  Instead, just show us the data -- your input and the desired output.  Thanks.

Follow the guidance here. http://sscce.org/
0
 
LVL 1

Author Comment

by:niken_asterina
ID: 39301124
Dear Experts,
In the one column of database, the formula :

f(9)=((@>8.5) AND (@<=9));f(6)=((@>9) AND (@<=11));f(1)=((@>11) AND (@>=15));

I want
If the formula like that, it means I get 9 if the input is 8.6, I get 6 if the input is 10 and I get
1 if the input is 13. (This is my goal)

Rgds,
Niken
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39301136
I'm mystified.  Is this an academic assignment?  I have never seen anything like this in the "real world" and I would not know of any design pattern that would address these kinds of formulae in a data base.  And I think the formula for f(1) is wrong anyway.  Probably should be @<=15 instead?

Is there any background or documentation you can point us to?  Or do you just want us to implement these exact three rules (not a generalized solution) in PHP?  If the latter it's not too hard.
http://www.laprbass.com/RAY_temp_niken_asterina.php

<?php // RAY_temp_niken_asterina.php
error_reporting(E_ALL);
echo '<pre>';

// f(9)=((@>8.5) AND (@<=9));f(6)=((@>9) AND (@<=11));f(1)=((@>11) AND (@>=15));
// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28173116.html#a39301124

Function Niken($x)
{
    // F(9)
    if ($x > 8.5)
    {
        if ($x <= 9)
        {
            return 9;
        }
    }

    // F(6)
    if ($x > 9)
    {
        if ($x <= 11)
        {
            return 6;
        }
    }

    // F(1)
    if ($x > 11)
    {
        if ($x <= 15)
        {
            return 1;
        }
    }

    // NONE OF THE ABOVE
    return -1;
}

// TEST THE FUNCTION
$arr = range(1,16);
foreach ($arr as $num)
{
    $val = niken($num);
    echo PHP_EOL . "FROM $num THE NIKEN() FUNCTION RETURNS $val";
}

Open in new window

0
 
LVL 1

Author Comment

by:niken_asterina
ID: 39301589
Dear Experts,
The existing application (Delphi) use this data.
If the database consists :

f(9)=((@>8.5) AND (@<=9));f(6)=((@>9) AND (@<=11));f(1)=((@>11) AND (@<=15));

The PHP coding should look like this

if (( $x>8.5) AND ($x<=9))
  {
  echo "9";
  }
elseif (($x>9) AND  ($x<=11))
  {
  echo "6";
  }
elseif (($x>11) AND  ($x<=15))
  {
  echo "1";
  }
  else
  {
  echo "wrong formula";
  }

How to make the formula automatically become look like the above code.

Regards,
niken
0
 
LVL 109

Assisted Solution

by:Ray Paseur
Ray Paseur earned 100 total points
ID: 39301789
make the formula automatically become look like the above code.
At this point it's not a question with an answer.  It's a requirement for application development and for something like that you should hire a professional developer.  This is going to take a while and will require a lot of well-constructed test data.  Any mid-to-high level PHP programmer can probably write a parser to generalize the script I posted above, and if I get some spare time later today or next week I may take up the task, but for now I'll sign off.

If you want to learn enough PHP to do this kind of work yourself, this article will point you to some good learning resources (and more importantly, it will keep you away from the less useful resources).
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

Best of luck with your project, ~Ray
0
 
LVL 23

Assisted Solution

by:Mysidia
Mysidia earned 400 total points
ID: 39303443
It seems that you are storing code in your database,  that you are expecting to execute in some world,  to decide what an output should be based on an input.

It's highly unusual to have programming code,  conditions,  or other  parseable structures in a relational database field

Are you expecting to generate a .PHP file  with contents that vary based on the contents of your database?     This is possible,  but it is clearly a complicated programming task.



You should be concerned first about the problem of parsing this code,  before you  even think of  attempting to provide a PHP equivalent.

The expression hasn't really been parsed until  you've actually mapped  it into data structures such as a parse tree;  where it's now possible to analyze (or execute)   the expression.

Now; if you are allowed to make certain assumptions about expression complexity and/or syntax,  the parsing process becomes simpler.


I understand there is  PHP-Peg  
and someone has a Jison port to PHP
https://github.com/robertleeplummerjr/jison/tree/master/ports/php

You can use such parser generator tools  to help you write the parser  to process the expression in the database,  and yield the parse tree --   then executable byte code  or PHP snippets.

If the expression language is simple enough,  then you can actually write ad-hoc code without too much trouble.    Otherwise,  writing a parser by hand is a process that takes expert developers weeks,   so obviously  the process of developing a parser is not something an EE expert would be prepared to do.


If you can guarantee that every expression looks  exactly like
f(1)=((@>11) AND (@>=15));

with just different numbers,  then you could write an ad-hoc parser to do it easily.


Change one operator.
Adjust spacing...
add more AND clauses, or delete a clause
change parenthesis grouping

or anything like that,  and you need a more complicated parser.
0
 
LVL 1

Author Closing Comment

by:niken_asterina
ID: 39303598
Dear Experts thank for your response,
Using
if ( eval('return ' .  $fformula[1] . ';') )  {

and parsing combination, solved my problem

Rgds
niken
0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question