php | Simple question on conditional statement - php

I'm new to php and I would like to have a conditional statement like this:
if ($foo != 'Any') { $condition .= '$this_foo == $foo &&';}
if ($bar != 'Any') { $condition .= '$this_bar == $bar &&';}
if ($txt != 'Any') { $condition .= '$this_txt == $txt &&';}
$condition .= '$num1 > 0 && $num2 < 1000';
if (...[php would parse the $condition variable])
{
someoperations
}
What is the proper syntax for the if statement to parse the variable $condition? So the conditional statement depends on the other variables and to prevent a long nested conditional statement.
Thanks in advance!

Well it's not exactly parsing, but you could evaluate your condition as the code is executed.
$condition = true;
if ($foo != 'Any') { $condition = $condition && ($this_foo == $foo);}
if ($bar != 'Any') { $condition = $condition && ($this_bar == $bar);}
if ($txt != 'Any') { $condition = $condition && ($this_txt == $txt);}
$condition = $condition && ($num1 > 0 && $num2 < 1000);
if ($condition)
{
someoperations
}
So let's say that $foo != 'Any' is true, that would result in
$condition = true && ($this_foo == $foo) && ($num1 > 0 && $num2 < 1000);
Let's pretend $this_foo == $foo, $num1 == 45 and $num2 == 2300
$condition = true && true && (true && false);
$condition = false;
and your if won't execute.

I believe what you want is
if (eval("return " . $condition)) {...}
Making sure to check for the FALSE case if the parsing fails.

Related

PHP if statement as variable

I have a variable ($statement) that will store dynamic content like the below:
($row[Gender] == "Female") && ($row[Grade] == "A" || $row[Grade] == "B" || $row[Grade] == "C1") && ($row[Race] == "African" || $row[Race] == "Coloured" || $row[Race] == "Indian" || $row[Race] == "White")
I want to then use this $statement in a if condition like so: if ($statment) {do logic here...}. This is used to match values in an array held in $row (e.g. $row[Gender] which has the value "Male").
Is this achievable and what's the best way to do it?
The whole method() is:
public function ApplyRuleset ($activeOpportunity, $step, $companyId, $projectId, $phaseId) {
// Get global vars
global $conn;
// Get non declined employees for this opportunity only
$getAllCandidates = $this->GetTalentPool ("normal", $step, $activeOpportunity[0]['oppID'], $companyId, $projectId, $phaseId);
// Get column slices
$columnSlices = GetSlices ($conn, $companyId, $projectId, $phaseId, 0);
// Split ruleset into manageable parts
$columnSets = explode (" AND ", $activeOpportunity[0]['rule']);
echo "<pre>";
// Check that we have all that we need
if (is_array ($getAllCandidates) && is_array ($columnSlices) && is_array ($columnSets)) {
// Get selected talent pool
foreach ($getAllCandidates as $row) {
// Format business rules
foreach ($columnSlices as $sliceValue) {
// Get the slices to match which facets were selected
$qualifiedName = preg_replace ('/\s+/', "", $sliceValue['facet']);
// Loop through column match
foreach ($columnSets as $set) {
// Get olumn match
$ruleMatch = explode (" -> ", $set);
$columnName = $ruleMatch[0];
$options = explode (",", $ruleMatch[1]);
// Match rule
for ($i = 0; $i < count ($options); $i++) {
// Write conditional statement
$statement .= '("$row[' . $columnName . ']" == "' . $options[$i] . '"';
$statement .= (count ($options) > 1 && $options[$i] !== end ($options)) ? " || " : ") && (";
}
}
break;
}
// Finalise statement
$editStatement = preg_replace ("/ && \($/", "", $statement);
$editStatement = preg_replace ("/ \(/", " ", $editStatement);
$editStatement = preg_replace ('/"\$/', "$", $editStatement);
$finaliseStatement = preg_replace ('/\]"/', "]", $editStatement);
// Do record match
if ($finaliseStatement) {
// Record matches, load into match array
$this->rulesetMatch[] = $row;
// Set required vars
$_REQUEST['selected'] = (array) $row[candidateId];
$_REQUEST['opportunityID'] = $activeOpportunity[0]['oppID'];
$_REQUEST['step'] = $step;
// Insert these records for round 1
//$this->AddCandidatesToOpportunity ();
}
}
}
// Return all the rows that matched and dedupe
return array_map ("unserialize", array_unique (array_map ("serialize", $this->rulesetMatch)));
}
You can use the result of the if in a variable called $statement like
$statement = (($row[Gender] == "Female") && ($row[Grade] == "A" || $row[Grade] == "B" || $row[Grade] == "C1") && ($row[Race] == "African" || $row[Race] == "Coloured" || $row[Race] == "Indian" || $row[Race] == "White"));
and then you can use this result in if statement as you wish
if ($statement === true) {
// ...
}

How can I optimise and improve getting 6 possible URL parameters

I am in the midst of writing a simple job board and I have the URL's filtering and working how I want, everything works - I just want to know if I can improve it, if there are any security concerns, and if it is horribly inefficient.
Take the following URL section - foo.com/in/london/at/google/do/design
I assign each section a variable and work out the location, company, and category.
Other use cases that work:
Switching the order - foo.com/at/google/in/london/do/design
Having less parameters - foo.com/in/london/at/google
My code to figure out all these variables is:
// Get the different possible page parameters
// Only allow alphanumeric, dashes, and commas
$regex = "[^a-zA-Z0-9,-]";
$a = isset($_GET["a"]) ? preg_replace("/".$regex."/", "", $_GET["a"]) : "";
$aa = isset($_GET["aa"]) ? preg_replace("/".$regex."/", "", $_GET["aa"]) : "";
$b = isset($_GET["b"]) ? preg_replace("/".$regex."/", "", $_GET["b"]) : "";
$bb = isset($_GET["bb"]) ? preg_replace("/".$regex."/", "", $_GET["bb"]) : "";
$c = isset($_GET["c"]) ? preg_replace("/".$regex."/", "", $_GET["c"]) : "";
$cc = isset($_GET["cc"]) ? preg_replace("/".$regex."/", "", $_GET["cc"]) : "";
if ($a == "in" && $aa != null) { $searchLocation = $aa; }
if ($b == "in" && $bb != null) { $searchLocation = $bb; }
if ($c == "in" && $cc != null) { $searchLocation = $cc; }
if ($a == "at" && $aa != null) { $searchCompany = $aa; }
if ($b == "at" && $bb != null) { $searchCompany = $bb; }
if ($c == "at" && $cc != null) { $searchCompany = $cc; }
if ($a == "do" && $aa != null) { $searchCategory = $aa; }
if ($b == "do" && $bb != null) { $searchCategory = $bb; }
if ($c == "do" && $cc != null) { $searchCategory = $cc; }
if ($a == "missinghtml") { $errorUrl = true; }
I'm looking at this thinking there must be a better to do this, and is this section secure?
Any thoughts on this are much appreciated. Like I say it works, but can it be better? Thanks :)

php if statement null and 0?

i'm having trouble executing my if statement
if($parent == $page->parent)
my dollar $parent = null and my $page->parent = 0 how do i fix this that they are equal?
i think it's a problem with the fact it doesn't know that null is equal to 0
$page = Page::find($id);
$parent = Input::get('parent'); // Null
i hope you guys can help me out i have to figure this out
here's my controller just in case you wan't to take a look at it
public function updateMenu($id)
{
$page = Page::find($id);
$parent = Input::get('parent');
$new_order = Input::get('index');
if($parent == $page->parent)
{
if($page->order_id > $new_order)
{
DB::table('pages')
->where('parent',$parent)
->where('order_id', '<', $page->order_id)
->increment('order_id');
}
else
{
DB::table('pages')
->where('parent',$parent)
->where('order_id', '>=', $page->order_id)
->decrement('order_id');
}
}
else
{
DB::table('pages')
->where('parent',$parent)
->where('order_id', '>=', $new_order)
->increment('order_id');
}
$page->order_id = Input::get('index');
$page->parent = Input::get('parent');
$page->save();
return $id;
}
I dont think 0 can be equals with NULL. maybe if($parent == $page->parent || ($parent == null && $page->parent == 0)) more helpful
Use the strict equality operator: === instead of ==
localhost> = 0 === null
false
localhost> = 0 == null
true
You can use:
if(is_null($parent) && ($page->parent==0))
{
}

If construct for multiple expressions

I'm working on something like this:
if ($varA != null & $varB = null){
$newthing = "Something else";
}
It doesn't seem to want to work. I've tried && for & but I can find a good reference for these and what they do.
EDIT: Going to try and clear up what my objective is.
I have three if statement that I want to execute whether or not some variables have value in an encoded URL. Those three statement are:
if ($lprice != null && $hprice == null){
$clauses[] = "MSTLISTPRC >= " . $lprice;
}
if ($hprice != null && $lprice == null)(
$clauses[] = "MSTLISTPRC <= " . $hprice;
}
if ($lprice != null && $hprice != null){
$clauses[] = "MSTLISTPRC BETWEEN " . $lprice . " AND " . $hprice;
}
The final if statement works, the first two don't. It's something with the PHP code itself because I'm testing it an echo to just output the query string and when I try to execute this, it fails. I don't know how to apply error handling so I haven't been using that.
You need to use && instead of & and == instead of =.
So:
if ($varA != null && $varB == null){
$newthing = "Something else";
}
if ($varA != null && $varB = null){
$newthing = "Something else";
}
this should be fine..

$var == 'string1' || 'string2' always returns TRUE

I want to echo $q2 and $q3 based on the question parameter, but it keeps giving me the same value regardless of the parameter's value. What did I do wrong?
$q1 = $_GET['question'];
if ($q1 == "domaina.com"||".domaina.com"||"domaina.co")
{
$q2 = 'domaina';
$q3 = 'DomainA';
}
elseif ($q1 == "domainb.com"||".domainb.com"||"domainb.co")
{
$q2 = 'domainb';
$q3 = 'DomainB';
}
elseif ($q1 == "domainc.com"||".domainc.com"||"domainc.co")
{
$q2 = 'domainc';
$q3 = 'DomainC';
}
else {
$q2 = 'noquestions';
$q3 = 'NoQuestions';
}
Any not empty string evaluates to true, so your first 'or' statement always evaluates to true.
The right to do is:
if ($q1 == "domaina.com"||$q1 == ".domaina.com"||$q1 == "domaina.co")
instead of
if ($q1 == "domaina.com"||".domaina.com"||"domaina.co")
tooooo repetitive.
$q1 = $_GET['question'];
$q2 = 'noquestions';
$q3 = 'NoQuestions';
if (preg_match('~^.?domain([a-c])\.com?$~',$q1,$m)) {
$q2 = 'domain'.$m[1];
$q3 = 'Domain'.strtoupper($m[1]);
}
By the way, to let you know, your way of writing a code, with no indents or spaces, is terrible.
You have an error in your == statement.
Should be like this :
$q1 = $_GET['question'];
if ($q1 == "domaina.com"|| $q1 == ".domaina.com"|| $q1 == "domaina.co")
{
$q2 = 'domaina';
$q3 = 'DomainA';
}
elseif ($q1 == "domainb.com"|| $q1 == ".domainb.com"||$q1 == "domainb.co")
{
$q2 = 'domainb';
$q3 = 'DomainB';
}
elseif ($q1 == "domainc.com"||$q1 == ".domainc.com"||$q1 == "domainc.co")
{$q2 = 'domainc';
$q3 = 'DomainC';
}
else {$q2 = 'noquestions';
$q3 = 'NoQuestions';
}
You could also use in_array :
$q1 = $_GET['question'];
if(in_array("$q1", array("domaina.com",".domaina.com",""domaina.co"")))
{
$q2 = 'domaina';
$q3 = 'DomainA';
}
//...
The following will always evaluate to true.
if ($q1 == "domaina.com"||".domaina.com"||"domaina.co")
You probably meant:
if ($q1 == "domaina.com"||$q1 == ".domaina.com"||$q1 == "domaina.co")
Your conditionals in the ifs are wrong. Try fixing those first.
if ($q1 == "domaina.com"||$q1 == ".domaina.com"||$q1 == "domaina.co")
{
...
}
you need to format it like so:
if ($q1 == "domaina.com" || $q1 == ".domaina.com" || $q1 == "domaina.co")
What you were doing was interpreted as:
if ($q1 == ("domaina.com" || ".domaina.com" || "domaina.co"))
// interpreted as:
if ($q1 == (((bool)"domaina.com" || (bool)".domaina.com" || (bool)"domaina.co"))
// interpreted as:
if ($q1 == ((true || true || true))
// interpreted as:
if ($q1 == true)
// interpreted as:
if ((bool)$q1 == true))
Note also that had you use the === operator instead, your last condition would have been the one that always evaluated to true instead of the first one, since you would be comparing a string with the result of a boolean operation.
You could simplify your if statements by using the strpos function like this:
$q1 = $_GET['question'];
if (strpos($q1, "domaina") === true) {
$q2 = "domaina";
$q3 = "DomainA";
} elseif (strpos($q1, "domainb") === true) {
$q2 = "domainb";
$q3 = "DomainB";
} elseif (strpos($q1, "domainc") === true) {
$q2 = "domainc";
$q3 = "DomainC";
} else {
$q2 = "noquestions";
$q3 = "NoQuestion";
}
I think you can simplify your code a bit:
<?php
$q1 = $_GET['question'];
$q2 = getDomain($q1);
$q3 = ucfirst(substr($q2, 0, -1)) + strtoupper(substr($q2, -1));
function getDomain($url){
$arrA = array('domaina.com', '.domaina.com', 'domaina.co');
$arrB = array('domaina.com', '.domaina.com', 'domaina.co');
$arrC = array('domaina.com', '.domaina.com', 'domaina.co');
$q1 = strtolower($url);
if(in_array($q1, $arrA))
return "domaina";
if(in_array($q1, $arrB))
return "domainb";
if(in_array($q1, $arrC))
return "domainc";
return '';
}
?>

Categories