[Completed] Strings in IF conditions

I have always wondered if this was possible and it would seriously improve my coding if there is a way around it.

Currently if I want to create a massive form I put everything in an array, so an example array would be:

[php]
$array = array(
‘name’ => array(‘type’ => ‘text’, ‘validate’ => ‘isString’),
‘company’ => array(‘type’ => ‘text’, ‘validate’ => ‘isString’, ‘optional’ => true)
);
[/php]

OK, not a massive one there but you get the point.

Anyway I would then cycle the post array and put in a value for each of the subarrays if it existed or a default value if necessary then when it comes to validating I can test like:

[php]
foreach ($array as $item)
{
if (!$item[‘optional’] || ($item[‘optional’] && strlen($item[‘value’]) > 0))
{
$item’validate’;
}
}
[/php]

And in the HTML output you can easily switch the type and print out text input, dropdowns etc.

The problem I am having now is that in the validating sometimes I need to say that one field is optional only under certain circumstances, so for example on credit card details you only want to take in an issue number if the card type is switch/solo. I thought that something like this would maybe work:

[php]
$array = array(
‘cardType’ => array(‘type’ => ‘select’, ‘options’ => array(‘Visa’, ‘MasterCard’, ‘Switch’, ‘Solo’)),
‘issueNumber’ => array(‘type’ => ‘text’, ‘validate’ => ‘isString’, ‘optional’ => ‘$array[‘cardType’][‘value’] == “Visa” || $array[‘cardType’][‘value’] == “MasterCard”’)
)’
[/php]

Then when validating:

[php]
if (!$array[‘issueNumber’][‘optional’])
{
// validate
}
[/php]

But alas PHP doesn’t parse the optional string before printing, you can test by trying:

[php]
$string = ‘1 == 0’;

if ($string)
{
print ‘Expression is true’;
}
[/php]

Even though 1 obviously does not equal 0 it prints the expression as the string has been set. I need it to parse the expression in the string and then use the boolean value from that expression in the conditional.

Is there a way?

{Having searched for quite some time… not holding my breath :D, thanks in advance to anyone who responds}

The PHP function you’re looking for is eval(). It parses a given string as though it were genuine PHP script. I wouldn’t recommend using it though, unless you truly know what you’re doing, as it poses a dangerous set of security holes.

An alternative I’d use, would be to give everything a default value, regardless of whether it’s optional or not. That way, you don’t have to worry about a mandatory field not being filled in.

Thanks, that is exactly what I was looking for, forgot that even existed.

I know there are security holes when using request variables but the validation code evaluated will only ever be fixed and hard coded in the PHP so it shouldn’t be too much of a risk as it will never be influenced by any user data.

Sponsor our Newsletter | Privacy Policy | Terms of Service