How make this if-statement more simple ? , as a function it's working well but i think it's not good on coding.
this is the code :
if (empty($checkMaxID))
{
$this->model->insert_temp_code($code_request,$cabang_code);
}
$checkHasTempCode = $this->model->checkHasTempCode($user_id);
if ($checkMaxID['tempcode_created_by'] != $user_id ) {
$data['code_request'] = str_pad($checkMaxID['tempcode_value'] + 1, 5, 0, STR_PAD_LEFT);
if (empty($checkHasTempCode) ) {
$this->model->insert_temp_code($data['code_request'],$cabang_code);
}
}
else
{
$data['code_request'] = $code_request;
}
`
anyone can help me please ?
Thank you
Use ternary operator when you have if else condition. Also, you can avoid nested if thorough multiple conditions in a single if statements. I hope this will helps.
$checkHasTempCode = $this->model->checkHasTempCode($user_id);
if (empty($checkMaxID)) {
$this->model->insert_temp_code($code_request,$cabang_code);
}
$data['code_request'] = ( $checkMaxID['tempcode_created_by'] != $user_id ) ?
str_pad($checkMaxID['tempcode_value'] + 1, 5, 0, STR_PAD_LEFT) : $code_request;
if ( empty($checkHasTempCode) && $checkMaxID['tempcode_created_by'] != $user_id ) {
$this->model->insert_temp_code($data['code_request'],$cabang_code);
}
Related
I have to evaluate a very long condition in PHP, so, to avoid errors and trying to write more readable code, I did the following:
//this returns 1 when true, and nothing when false, although expected TRUE or FALSE
$isNameValid=strlen($dataDecoded['nombre'])>=3;
$isDescriptionValid=(strlen($dataDecoded['descripcion'])>=10) && strlen($dataDecoded['descripcion'])<=300;
$isPriceValid=$dataDecoded['precio'] >0;
$isImageValid=(($dataDecoded['imagen'] != "") && ($dataDecoded['imagen'] != NULL) );
And now, I can make the following:
if($isNameValid==1 && $isDescriptionValid==1 && $isPriceValid==1 && $isImageValid==1)
{
echo "ok";
}
else{
echo "no";
}
It seems to work fine, but maybe is a weird way of doing things. I wanted to avoid the following, which I find more confusing and easy to make a mistake
if(strlen($dataDecoded['nombre'])>=3 && ... && ...)
Is there a better way to do that? Is wrong what I did? Thanks
I don't care for creating extra variables here; this makes code difficult to maintain and unreusable. I'd recommend breaking your validation logic into easy-to-read, maintainable, reusable functions:
function valid($data) {
return validName($data['nombre']) &&
validDescription($data['descripcion']) &&
validPrice($data['precio']) &&
validImage($data['imagen']);
}
function validName($name) {
return strlen($name) >= 3;
}
function validDescription($desc) {
return strlen($desc) >= 10 && strlen($desc) <= 300;
}
function validPrice($price) {
return $price > 0;
}
function validImage($image) {
return $image !== "" && $image != NULL;
}
$dataDecoded = [
"nombre" => "foo",
"descripcion" => "foo bar foo bar",
"precio" => 15,
"imagen" => "foo.png"
];
// now your main code is beautiful:
echo (valid($dataDecoded) ? "ok" : "no") . "\n";
Yes, that is acceptable. However, your variables there are all boolean, so you don't even need the ==1.
if($isNameValid && $isDescriptionValid && $isPriceValid && $isImageValid)
It really depends on how you want to handle it.
Is switch an option or a viable one?
Is ternary if prettier or handy?
From what I see, I'm guessing you have a validation purpose and a operating incoming depending on the validation. Why not create a function or a class that handles your input and validates? And in there, you can have all the dirty code you'd want. On your logical code, you'd just have to do (e.g of a class)
$someClass = new SomeClass();
$someClass->validate($fields);
if ($someClass->isValidated()) ...
This way, you'd actually follow some standards whereas the purpose of it would be to work as a validator for (all of? depends on your needs) your data
E.g of ternary ifs
$isNameValid = count($dataDecoded['nombre'])>=3 ? true : false;
$isDescriptionValid = count($dataDecoded['descripcion']) >= 10 && count($dataDecoded['descripcion']) <= 300 ? true : false;
$isPriceValid = count($dataDecoded['precio']) > 0 ? true : false;
$isImageValid = empty($dataDecoded['imagen']) === false ? true : false;
if ($isNameValid && $isDescriptionValid && $isPriceValid && $isImageValid) ...
I am trying to use an if statement in a variable in wordpress such that if the page-id is 17711 the variable should be equal to 4 if not true is should be equal to intval( get_option('wp_estate_prop_no', '') );
The code i am trying to use is:
$prop_no = if (is_page(17711)) { 4}
else {
intval( get_option('wp_estate_prop_no', '') );
}
I'm unsure what your is_page function does, but you should be able to use PHP's ternary operator to achieve an identical effect.
$prop_no = (is_page(17711) ? 4 : intval( get_option('wp_estate_prop_no', '')));
Try this:
$prop_no = (is_page(17711)?4:intval(get_option('wp_estate_prop_no,''));
Read about here : https://davidwalsh.name/php-ternary-examples
yo can use $proper_no = is_page(17711) ? 4 : intval( get_option('wp_estate_prop_no', ''));
or.
if(is_page(17711) == 4){
$proper_no = 4;
}else{
$proper_no = get_option('wp_estate_prop_no', '');
}
how can i use following in code in switch case:
if($_GET['test']=='') { $test='demo';} else { $test=$_GET['test'];}
if($_GET['test1']=='') { $test1='demo';} else { $test1=$_GET['test1'];}
if($_GET['test2']=='') { $test2='demo';} else { $test2=$_GET['test2'];}
if($_GET['test3']=='') { $test3='demo';} else { $test3=$_GET['test3'];}
if($_GET['test4']=='') { $test4='demo';} else { $test4=$_GET['test4'];}
if($_GET['test5']=='') { $test5='demo';} else { $test5=$_GET['test5'];}
Thanx in advance
Why use a switch here? You can just use a simple foreach and create the variables using variable variables:
foreach (array('test', 'test1', 'test2', 'test3', 'test4', 'test5') as $var) {
$$var = isset($_GET[$var]) ? $_GET[$var] : '';
}
Alternatively, look into filter
You could always use a ternary operator ( http://www.tuxradar.com/practicalphp/3/12/4 )
$test = $_GET['test'] == '' ? 'demo' : $_GET['test'] ;
$test1 = $_GET['test1'] == '' ? 'demo' : $_GET['test1'] ;
.. etc ..
Although just iterating through repetitive variables could be done with a loop far easier.
Very simple question... I'm having an issue that an if statement isn't working? All I want is the statement to be that if when $quantity is not equal to 20, or 40, or 80, or 160 to display here.
if($quantity != '20' || $quantity !='40' || $quantity != '80' || $quantity != '160')
{
echo "here";
}
Any suggestions would be appreciated. :)
Try this, it's cleaner (IMO) :
if (!in_array($quantity, array(20, 40, 80, 160))
{
echo "here";
}
Else just replace || with &&.
replace the || (or) by && (and) ;)
This way you check if something is 20, then you check if something is 40, etc. So when you have for example 40 the first check (!=20) just returns True (since you are using or's) and it never reaches the second or further check.
If $quantity is 40, it is not 20, so the condition is satisfied.
Study and understand http://en.wikipedia.org/wiki/De_Morgan%27s_Law .
If you don't want $quantity to be equal to any of them, you need to change your '||' or operator to the and operator '&&'.
I made it easier to check for higher numbers, by figuring out your algorithm.
Iterative:
<?php
for ($i = 0; $i <= 3; $i++) {
if ($quantity == pow(2,$i)*20) { echo "not here"; goto matched; }
}
echo "here";
matched:
?>
More functional:
<?php
if (!in_array($quantity,
array_map(
function ($i) { return pow(2,$i)*20; },
range(0,3)
)
)) {
echo "here";
} else {
echo "not here";
}
?>
I have a database table that stores various type of operators and values that make expressions like
if(mydBVal1 mydBExpression mydBval2)
{
// do something....!
}
Here is my code thats shows and example of what I want to say and the help I require
e.g:
$data['myValue'] = 100;
$data['operator'] = "<";
$data['comparison_value'] = 150
if( $data['myValue'] . $data['operator'] . $data['comparison_value'] )
{
///do something......
}
I want that if condition to be read as if(100 < 150){}, but the if condition expression is not working properly!
any one here know how I can make it work?
I think you want to use the eval() function.
Be very careful about sanitising the data from the database before evaling it though as you could allow users to execute PHP code that you don't want them to.
$data['myValue']=100;
$data['operator']="<";
$data['comparison_value']= 150;
$eval = sprintf("return(%d %s %d);", $data['myValue'], $data['operator'], $data['comparison_value']);
if(eval($eval))
{
Also you can take a look into php assert
php.net/assert
<?php
var_dump(assert("1 == 1"));
var_dump(assert("1 === null"));
?>
Sample code I used related to my project:
$assert_statement =
(($typecriteria != 'IS_NULL' || $typecriteria != 'NOT_NULL' ) ? "'".$value."'" : '' )
. " " . $typecriteria . " '" . $criteriavalue."'";
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_BAIL, 0);
assert_options(ASSERT_QUIET_EVAL, 1);
if ( $debug >= 1 ) {
print __METHOD__." assert debug ".$assert_statement."<br>";
var_dump(assert( $assert_statement ));
}
if (assert( $assert_statement ) === true )
{
return true;
}