Logic of if ifelse and elseif in php - php

I am comparing seven (7) boolean values 1 (true) or 0 (false) of a primary set and five (5) of a secondary set with an addition of 2 n/a choices. If all 12 come back as true, then the $class is set to Reuse. If the primary set is True and Secondary is false then it comes back as Resale. If any of the primary set comes back False, it's set to Repair. This is what I have so far, and don't get back any syntax errors, but the "class" is coming back incorrect.
<?php
$primary = false;
$class = null;
if ($_POST['poweradapter'] == "1"
&& $_POST['mobocpu'] == "1"
&& $_POST['memory'] == "1"
&& $_POST['harddrive'] == "1"
&& $_POST['screen'] == "1"
&& $_POST['battery'] == "1"
&& $_POST['hinge'] == "1")
{
$class = "Reuse";
$primary = true;
}
else
{
$class = "Repair or Recycle";
}
if ($primary
&& in_array($_POST['opticaldrive'], ["1", "2"])
&& in_array($_POST['floppydrive'], ["1", "2"])
&& $_POST['usb'] == "1"
&& $_POST['trackpad'] == "1"
&& $_POST['keyboard'] == "1")
{
/*
* "secondary" is implicit here, but we never did anything with the
* $secondary variable in the original script
*/
$class = "Reuse";
}
else
{
$class = ($primary) ? "Reuse" : "Repair or Recycle";
}
?>
Final working script
<?php
$primary = false;
$class = null;
if ($_POST['poweradapter'] == "1"
&& $_POST['mobocpu'] == "1"
&& $_POST['memory'] == "1"
&& $_POST['harddrive'] == "1"
&& $_POST['screen'] == "1"
&& $_POST['battery'] == "1"
&& $_POST['hinge'] == "1")
{
$primary = true;
$class = "Resale";
}
else
{
$class = "Repair or Recycle";
}
if ($primary && in_array($_POST['opticaldrive'], ["1", "2"])
&& in_array($_POST['floppydrive'], ["1", "2"])
&& $_POST['usb'] == "1"
&& $_POST['trackpad'] == "1"
&& $_POST['keyboard'] == "1")
{
$class = "Reuse";
}
?>

The main problem is that you're using double equals in the body of the first if statement.
$class == "Reuse";
$primary == "True";
should be
$class = "Reuse";
$primary = "True";
There are a lot of things you could do to make this more readable and maintainable, but the bug is the equality vs assignment issue.
Here is what I would do to make this easier to work with:
<?php
$primary = false;
$class = null;
if ($_POST['poweradapter'] == "1"
&& $_POST['mobocpu'] == "1"
&& $_POST['memory'] == "1"
&& $_POST['harddrive'] == "1"
&& $_POST['screen'] == "1"
&& $_POST['battery'] == "1"
&& $_POST['hinge'] == "1")
{
$class = "Reuse";
$primary = true;
}
else
{
$class = "Repair or Recycle";
}
if ($primary
&& in_array($_POST['opticaldrive'], ["1", "2"])
&& in_array($_POST['floppydrive'], ["1", "2"])
&& $_POST['usb'] == "1"
&& $_POST['trackpad'] == "1"
&& $_POST['keyboard'] == "1")
{
/*
* "secondary" is implicit here, but we never did anything with the
* $secondary variable in the original script
*/
$class = "Reuse";
}
else
{
$class = ($primary) ? "Resale" : "Repair or Recycle";
}
Hope this helps.
[Edit]
Since you're still having trouble with the logic itself, this is an ideal case for unit testing. Here's a little script you can run from the command line to test and fine tune your logic without having to worry about getting PHPUnit set up:
<?php
class MyService
{
public static $CLASS_REUSE = 'Reuse';
public static $CLASS_RESALE = 'Resale';
public static $CLASS_REPAIR_RECYCLE = 'Repair or Recycle';
public static function determineClassForInputParameters($params)
{
$primary = false;
$class = null;
if ($params['poweradapter'] == "1"
&& $params['mobocpu'] == "1"
&& $params['memory'] == "1"
&& $params['harddrive'] == "1"
&& $params['screen'] == "1"
&& $params['battery'] == "1"
&& $params['hinge'] == "1")
{
$primary = true;
}
if ($primary
&& in_array($params['opticaldrive'], ["1", "2"])
&& in_array($params['floppydrive'], ["1", "2"])
&& $params['usb'] == "1"
&& $params['trackpad'] == "1"
&& $params['keyboard'] == "1")
{
$class = self::$CLASS_REUSE;
}
else
{
$class = ($primary) ? self::$CLASS_RESALE : self::$CLASS_REPAIR_RECYCLE;
}
return $class;
}
}
class MyServiceTest
{
public function __construct()
{
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);
assert_options(ASSERT_CALLBACK, array($this, 'assertHandler'));
}
public function determineClassForInputParametersShouldReturnReuse()
{
$params = [
'poweradapter' => 1,
'mobocpu' => 1,
'memory' => 1,
'harddrive' => 1,
'screen' => 1,
'battery' => 1,
'hinge' => 1,
'opticaldrive' => 1,
'floppydrive' => 1,
'usb' => 1,
'trackpad' => 1,
'keyboard' => 1
];
$class = MyService::determineClassForInputParameters($params);
if (assert($class == MyService::$CLASS_REUSE, 'Expected class ' . MyService::$CLASS_REUSE . ', found ' . $class))
{
echo "determineClassForInputParametersShouldReturnReuse Passed\n";
}
}
public function determineClassForInputParametersShouldReturnResale()
{
$params = [
'poweradapter' => 1,
'mobocpu' => 1,
'memory' => 1,
'harddrive' => 1,
'screen' => 1,
'battery' => 1,
'hinge' => 1,
'opticaldrive' => 1,
'floppydrive' => 1,
'usb' => 1,
'trackpad' => 1,
'keyboard' => 0
];
$class = MyService::determineClassForInputParameters($params);
if (assert($class == MyService::$CLASS_RESALE, 'Expected class ' . MyService::$CLASS_RESALE . ', found ' . $class))
{
echo "determineClassForInputParametersShouldReturnResale Passed\n";
}
}
public function determineClassForInputParametersShouldReturnRePairOrRecycle()
{
$params = [
'poweradapter' => 0,
'mobocpu' => 1,
'memory' => 1,
'harddrive' => 1,
'screen' => 1,
'battery' => 1,
'hinge' => 1,
'opticaldrive' => 1,
'floppydrive' => 1,
'usb' => 1,
'trackpad' => 1,
'keyboard' => 1
];
$class = MyService::determineClassForInputParameters($params);
if (assert($class == MyService::$CLASS_REPAIR_RECYCLE, 'Expected class ' . MyService::$CLASS_REPAIR_RECYCLE . ', found ' . $class))
{
echo "determineClassForInputParametersShouldReturnRePairOrRecycle Passed\n";
}
}
public function assertHandler($file, $line, $code, $desc = null)
{
echo "Assertion failed at $file:$line: $code";
if ($desc)
{
echo ": $desc";
}
echo "\n";
}
}
$tester = new MyServiceTest();
$tester->determineClassForInputParametersShouldReturnReuse();
$tester->determineClassForInputParametersShouldReturnResale();
$tester->determineClassForInputParametersShouldReturnRePairOrRecycle();
You may find it useful to adopt some of the techniques shown in the test, like encapsulating your logic in a service class to make it easier to test and use in multiple places, using static variables for your "class" names to prevent typo errors, etc. Or you can just tune your logic with this and copy it into your existing code.
It may seem like a lot of overhead, but the few minutes it takes to set up tests for your logic far outweighs the hours you can waste trying to figure it out by submitting requests through your front end.

Here try to first set primary and secondary flag to true or false, then compare for the conditions, below is the code snippet, hope this helps.
There are two problems
1. in the first if you are setting $primary as $primary == "True" instead of $primary="True" , so here instead of setting the primary flag, it is comparing whether $primary is true. same is the case with $class.
in the second if statement -$_POST['floppydrive']=="1" or"2" is always true , so it results in true block of if getting executed every time, here or "2", can be changed to - ($_POST['floppydrive']=="1" || $_POST['floppydrive']=="2")
This should get you desired result
<?php
//setting primary flag
if ($_POST['poweradapter']=="1" && $_POST['mobocpu']=="1" && $_POST['memory']=="1" && $_POST['harddrive']=="1" && $_POST['screen']=="1" && $_POST['battery']=="1" && $_POST['hinge']=="1"){
$primary = "True";
}else{
$primary = "False";
}
//setting secondary flag
if (($_POST['opticaldrive']=="1" || $_POST['opticaldrive']== "2") && ($_POST['floppydrive']=="1" || $_POST['floppydrive']== "2") && $_POST['usb']=="1" && $_POST['trackpad']=="1" && $_POST['keyboard']=="1"){
$secondary = "True";
}else{
$primary = "False";
}
//setting the class now
if ($primary == "True" && $secondary=="True") {
$class = "Reuse";
}
elseif ($primary == "True" && $secondary=="False") {
$class = "Resale";
}
else{
$class = "Repair or Recycle";
}
?>
output
Power Adapter: 1
Motherboard: 1
Memory: 1
Hard/SSD Drive: 1
Screen: 1
Battery: 0
Screen Hinge: 0
USB Ports: 0
Track/Touch Pad: 0
Keyboard: 0
Optical Drive: 0
Floppy Drive: 1
was added with an Class of Repair or Recycle

Related

PHP Elseif always returning false, multiple conditions

I'm trying to make an helper php-function that's going to return true/false if the user got right access level. The access level is set when the user logs in. The problem is that the function always return false. The function is located in a "class" php-file that's included(with include_once) on the page I want to use it.
I'm kinda new to php, but the if conditions seems to be right.
I have tested to log in as admin and "economy", but it doesn't return true.
I also have tried to echoing the value that is sent as an parameter and even checking that the access level is right(by echoing the value) before the elseif statement.
const AccessLevelUser = 0;
const AccessLevelAdmin = 1;
const AccessLevelManager = 2;
const AccessLevelEconomy = 3;
public static function hasAccessLevel($requiredAccess) {
//file_put_contents('logg.txt', $logg);
if( !isset($_SESSION['accesslevel']) ) {
header("location:index.php?location=login");
exit;
}elseif ( $requiredAccess == AccessLevelAdmin && $_SESSION['accesslevel'] == AccessLevelAdmin ) {
echo "Admin True";
return true;
}elseif( $requiredAccess == AccessLevelEconomy && ($_SESSION['accesslevel'] == 3 || $_SESSION['accesslevel'] == 1) ) {
echo "Economy True";
return true;
}elseif( $requiredAccess == AccessLevelManager && ($_SESSION['accesslevel'] == 2 || $_SESSION['accesslevel'] == 1) ) {
echo "Manager True";
return true;
}elseif( $requiredAccess == AccessLevelUser && ($_SESSION['accesslevel'] == 0 || $_SESSION['accesslevel'] == 1) ) {
echo "User True";
return true;
}else{
echo "FALSE!";
return false;
}
}

Making IF ELSE statement with combinations of choice

Currently I'm making an application to suggest a car that suits the users' preferences based on their selection. I'd skip the HTML form but the choices are as follow:
Type: MPV, SUV, Sedan
Passengers: 5, 7
Engine: Gasoline, Diesel
Budget: Low, Medium, High, Luxury
Here I'm trying to make a combination because I want that every single choice counts. Therefore this is what I've done so far:
if (isset($_POST['submit'])
{
$type = $_POST['type'];
$passengers = $_POST['passengers'];
$engine = $_POST['engine'];
$budget = $_POST['budget'];
if ($type == 'MPV' && $passengers == 5 && $engine == 'Gasoline' && $budget == 'Low')
{
// execute my function here
}
else if ($type == 'MPV' && $passengers == 7 && $engine == 'Gasoline' && $budget == 'Low')
{
// execute my function here
}
else if ($type == 'MPV' && $passengers == 5 && $engine == 'Diesel' && $budget == 'Low')
{
// execute my function here
}
// and it goes on and on......
I know my problem is I will have to keep making if/elseif function until I list every single possible combination. Now is there any better way to do this? I need to get every single possible combination because there are additional calculations to be done in my custom function.
Here is my custom function:
public function calculateDetails($displacement_bottom, $displacement_top, $price_bottom, $price_top, $clearance)
{
$stmt = $connect->prepare("SELECT id, brand, name FROM cars
WHERE type = '$type'
AND displacement BETWEEN '$displacement_bottom' AND '$displacement_top'
AND price BETWEEN '$price_bottom' AND '$price_top'
AND clearance = '$clearance'
AND passengers = '$passengers'
AND engine = '$engine'
LIMIT BY 3");
$stmt->execute();
while ($row = $stmt->fetch())
{
$result = echo htmlspecialchars($row['brand'])." ".htmlspecialchars($row['name']);
}
return $result;
}
So I can do this
if ($type == 'MPV' && $passengers == 5 && $engine == 'Gasoline' && $budget == 'Low')
{
$suggestion = calculateDetails(1500, 2000, 100, 150, 'Medium');
echo $suggestion;
} else if ($type == 'MPV' && $passengers = 7 && $engine == 'Gasoline' && $budget = 'Low')
{
// continue on and on...
}
Since I couldn't find a way to simplify the if/else "loop" (and I started thinking about giving up :( ), I came into few new functions
public function typeDetails($type)
{
if ($type == 'MPV')
{
$detailed_type = echo "1500 AND 2000";
}
else if ($type == 'SUV')
{
$detailed_type = echo "2000 AND 3500";
}
else
{
$detailed_type = echo "2000 AND 3000";
}
return $detailed_type;
}
public function budgetDetails($budget)
{
if ($budget == 'Low')
{
$detailed_price = echo "100 AND 150";
}
else if ($type == 'Medium')
{
$detailed_price = echo "150 AND 250";
}
else if ($type == 'High')
{
$detailed_price = echo "250 AND 450";
}
else
{
$detailed_price = echo "450 AND 800";
}
return $detailed_price;
}
public function groundClearance($type)
{
if ($type == 'MPV')
{
$ground_clearance = "Medium";
}
else if ($type == 'SUV')
{
$ground_clearance = "High";
}
else
{
$ground_clearance = "Low";
}
return $ground_clearance;
}
In which I hope to be able to do this instead
$type = $_POST['type'];
$budget = $_POST['budget'];
$displacement = typeDetails($type);
$price = budgetDetails($budget);
// same function but with simplified where clause
$suggestion = calculateDetails($displacement, $price, $clearance);
echo $suggestion;
I'm too tired to continue today, but thanks to you guys I came up into few more ideas. I appreciate all the replies and comments given here. I might not be that good in PHP, therefore I want to learn how to make things simpler
There is not much you can do here. As an alternative option, you may create kind of a matrix for your models using multi level array:
$matrix = [
'MPV' => [
'Diesel' => [
5 => [
'Low' => function() { ... },
'Medium' => function() { ... },
],
],
'Gasoline' => [ ... ],
],
'SUV' => [ ... ],
];
if (isset($matrix[$type][$engine][$passengers][$budget])) {
$matrix[$type][$engine][$passengers][$budget]();
}
You may also reuse some functions if they don't differ too much or set special constants instead of functions to be passed to a single custom method. It really depends on the actual functionality you have for each combination.
Well I will pick that your function will be to choose a car, so you can add all options that you have (ex 3 different cars) into your database and have 4 values for each :
Type
Passengers
Engine
Budget
And set default value for each car :
ex for this condition :
$type == 'MPV' && $passengers == 5 && $engine == 'Gasoline' && $budget == 'Low'
Type = 1
Passengers = 1
Engine = 1
Budget = 1
And regarding clients choosing different options, you can filter your query and select the car that match the search !
Ex :
$query = ("SELECT * FROM car WHERE type = :type AND passengers = :passengers AND engine = :engine AND budget = :budget");

Condition statement in value attr CGridView Yii

when I do this in CgridView:
'value' => '$data->status == 1 ? "Payed" : "None" ',
it works, but when I do this:
'value' => 'if ($data->status == 1) { echo "Payed"; } else if($data->status == 2) { echo "Two"; } else { echo "None"; } '.
What I need to do to make work the second statement, or how I need to rewrite it?
Convert your statement to use ternary if:
'value' => '$data->status == 1 ? "Payed": ($data->status == 2 ? "Two" : "None")',
You could also use a function instead to give a bit more flexibility and make it more readable:
'value' => function($row, $data ) {
if ($data->status == 1) { return "Payed"; }
else if($data->status == 2) { return "Two"; }
else { return "None"; }
}
Just in case :
I've tried topher's solution and I found out that I had to switch param like that :
'value' => function($data, $row ) {
if ($data->status == 1) { return "Payed"; }
else if($data->status == 2) { return "Two"; }
else { return "None"; }
}
With topher's solution $data->attribute_name did not work and was, in fact, the row instead of the model..
Perhaps, if you don't need $row, don't pass it.
my solution:
function checkStatus($status)
{
if ($status == 1) {
return "opl";
} else if ($status == 2) {
return "nal";
} else {
return "neopl";
}
}
'value' => 'checkStatus($data->status)',
But your will work too) I will accept answer)

php | more effective function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I have a function and it works. Please check below:
public static function checkAccessLevel($user, $level) {
public static function checkLevel($user, $level) {
if ($level == "1") {
if (!$user->usertype == 1) {
return array(
'error' => 'Please login before', 'errortype' => 0
);
}
} else if ($level == "2") {
if (!$user->usertype == 2) {
return array(
'error' => 'Please login before', 'errortype' => 0
);
}
} else if ($level == "1,2") {
if (!$user->usertype == 1 || !$user->usertype == 2) {
return array(
'error' => 'Please login before', 'errortype' => 0
);
}
} else {
return array(
'error' => 'Please login before', 'errortype' => 0
);
}
}
I'm looking the way for code optimization. Is it possible to rewrite this function?
$level is always comma separated, just break it and check:
public static function checkLevel($user, $level)
{
$level = explode(',', $level);
if(!in_array($user->usertype, $level))
return array(
'error' => 'Please login before',
'errortype' => 0
);
}
and better yet, throw an Exception or return a boolean.
public static function checkLevel($user, $level)
{
if (($level == "1" && ! $user->usertype == 1) ||
($level == "2" && ! $user->usertype == 2) ||
($level == "1,2" && ! in_array($user->usertype, array(1, 2))) ||
! in_array($level, array("1", "2", "1,2"))) {
return array(
'error' => 'Please login before', 'errortype' => 0
);
}
}
First of all consider using switch, it should be more readable.
Then you may group your conditions, instead of:
} else if ($level == "1,2") {
if (!$user->usertype == 1 || !$user->usertype == 2) {
group them together:
(($level == "1,2") && (!$user->usertype == 1 || !$user->usertype == 2))
Then you may use temporary variable $result:
$result = array('Please login...
and return it at the end, instead of using return keyword in every step, it should help you in debugging.
Also I suggest to read Martin Fowlers book about refactoring which will give you many good advice.
You could use a switch statement instead of an if statement, like so:
public static function checkLevel($user, $level) {
$result = array();
switch($level) {
case '1':
if( $user->usertype == 1) {
$result = array(
'error' => 'Please login before', 'errortype' => 0
);
}
break;
// More cases for each level.
default:
$result = array(
'error' => 'Please login before', 'errortype' => 0
);
}
return $result;
}

Simple PHP Condition help: if($Var1 = in list($List) and $Cond2) - Is this posslbe?

Is this a possible function?
I need to check if a variable is existent in a list of ones I need to check against and also that cond2 is true
eg
if($row['name'] == ("1" || "2" || "3") && $Cond2){
doThis();
}
It's not working for me and all I changed in the copy paste was my list and the variable names
if(in_array($row['name'], array('1', '2', '3')) && $Cond2) {
doThis();
}
PHP's in_array() docs: http://us.php.net/manual/en/function.in-array.php
You're lookin for the function in_array().
if (in_array($row['name'], array(1, 2, 3)) && $cond2) {
#...
if (in_array($name , array( 'Alice' , 'Bob' , 'Charlie')) && $condition2 ) {
/* */
}
use in_array function
if(in_array($row['name'], array(1,2,3)) && $cond2){
do ...
}
$name = $row['name'];
if (($name == "1" || $name == "2" || $name == "3") && $cond2)
{
doThis();
}
I have something simpler than that, if it's still possible...
if(strpos("1,2,3", $row['name']) !== false) && $Cond2) {
doThis();
}

Categories