Using an if statement in a variable in php - php

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', '');
}

Related

How to make simple if statement bubble style?

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);
}

Php mail() echo showing all the time [duplicate]

I'm trying to check whether a $_POST exists and if it does, print it inside another string, if not, don't print at all.
something like this:
$fromPerson = '+from%3A'.$_POST['fromPerson'];
function fromPerson() {
if !($_POST['fromPerson']) {
print ''
} else {
print $fromPerson
};
}
$newString = fromPerson();
Any help would be great!
if( isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
Simple. You've two choices:
1. Check if there's ANY post data at all
//Note: This resolves as true even if all $_POST values are empty strings
if (!empty($_POST))
{
// handle post data
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
(OR)
2. Only check if a PARTICULAR Key is available in post data
if (isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
Surprised it has not been mentioned
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['fromPerson'])){
Everyone is saying to use isset() - which will probably work for you.
However, it's important that you understand the difference between
$_POST['x'] = NULL; and $_POST['x'] = '';
isset($_POST['x']) will return false on the first example, but will return true on the second one even though if you tried to print either one, both would return a blank value.
If your $_POST is coming from a user-inputted field/form and is left blank, I BELIEVE (I am not 100% certain on this though) that the value will be "" but NOT NULL.
Even if that assumption is incorrect (someone please correct me if I'm wrong!) the above is still good to know for future use.
isset($_POST['fromPerson'])
The proper way of checking if array key exists is function array_key_exists()
The difference is that when you have $_POST['variable'] = null it means that key exists and was send but value was null
The other option is isset() which which will check if array key exists and if it was set
The last option is to use empty() which will check if array key exists if is set and if value is not considered empty.
Examples:
$arr = [
'a' => null,
'b' => '',
'c' => 1
];
array_key_exists('a', $arr); // true
isset($arr['a']); // false
empty($arr['a']); // true
array_key_exists('b', $arr); // true
isset($arr['b']); // true
empty($arr['b']); // true
array_key_exists('c', $arr); // true
isset($arr['c']); // true
empty($arr['c']); // false
Regarding your question
The proper way to check if value was send is to use array_key_exists() with check of request method
if ($_SERVER['REQUEST_METHOD'] == 'POST' && array_key_exists('fromPerson', $_POST)
{
// logic
}
But there are some cases depends on your logic where isset() and empty() can be good as well.
In that case using method isset is not appropriate.
According to PHP documentation: http://php.net/manual/en/function.array-key-exists.php
(see Example #2 array_key_exists() vs isset())
The method array_key_exists is intended for checking key presence in array.
So code in the question could be changed as follow:
function fromPerson() {
if (array_key_exists('fromPerson', $_POST) == FALSE) {
return '';
} else {
return '+from%3A'.$_POST['fromPerson'];
};
}
$newString = fromPerson();
Checking presence of array $_POST is not necessary because it is PHP environment global variable since version 4.1.0 (nowadays we does not meet older versions of PHP).
All the methods are actually discouraged, it's a warning in Netbeans 7.4 and it surely is a good practice not to access superglobal variables directly, use a filter instead
$fromPerson = filter_input(INPUT_POST, 'fromPerson', FILTER_DEFAULT);
if($fromPerson === NULL) { /*$fromPerson is not present*/ }
else{ /*present*/ }
var_dump($fromPerson);exit(0);
Try
if (isset($_POST['fromPerson']) && $_POST['fromPerson'] != "") {
echo "Cool";
}
I would like to add my answer even though this thread is years old and it ranked high in Google for me.
My best method is to try:
if(sizeof($_POST) !== 0){
// Code...
}
As $_POST is an array, if the script loads and no data is present in the $_POST variable it will have an array length of 0. This can be used in an IF statement.
You may also be wondering if this throws an "undefined index" error seeing as though we're checking if $_POST is set... In fact $_POST always exists, the "undefined index" error will only appear if you try to search for a $_POST array value that doesn't exist.
$_POST always exists in itself being either empty or has array values.
$_POST['value'] may not exist, thus throwing an "undefined index" error.
Try isset($_POST['fromPerson'])?
if (is_array($_POST) && array_key_exists('fromPerson', $_POST)) {
echo 'blah' . $_POST['fromPerson'];
}
if( isset($_POST['fromPerson']) ) is right.
You can use a function and return, better then directing echo.
I like to check if it isset and if it's empty in a ternary operator.
// POST variable check
$userID = (isset( $_POST['userID'] ) && !empty( $_POST['userID'] )) ? $_POST['userID'] : null;
$line = (isset( $_POST['line'] ) && !empty( $_POST['line'] )) ? $_POST['line'] : null;
$message = (isset( $_POST['message'] ) && !empty( $_POST['message'] )) ? $_POST['message'] : null;
$source = (isset( $_POST['source'] ) && !empty( $_POST['source'] )) ? $_POST['source'] : null;
$version = (isset( $_POST['version'] ) && !empty( $_POST['version'] )) ? $_POST['version'] : null;
$release = (isset( $_POST['release'] ) && !empty( $_POST['release'] )) ? $_POST['release'] : null;
I recently came up with this:
class ParameterFetcher
{
public function fetchDate(string $pDate):string{
$myVar = "";
try{
if(strlen($_POST[$pDate]) > 0){
$myVar = $_POST[$pDate];
}
}catch (Exception $faild){
die("field NULL or not set for $pDate");
}
[ ... other stuff ]
to fetch a date obviously, but it can take ANY post param. You can also check for GET this way.

PHP Array Conditional Short Syntax

Here is what I have, I know I can rewrite my conditional syntax but I just wanted to see if there was something else I can do with what I have.
$sleeping[] = ($a->day_bed == 1) ? 'Day Bed' : false;
$sleeping[] = ($a->fold_up_bed == 1) ? 'Fold Up Bed' : false;
$sleeping[] = ($a->murphy_bed == 1) ? 'Murphy Bed' : false;
$sleeping[] = ($a->trundle_bed == 1) ? 'Trundle Bed' : false;
I'm trying to test for an empty array or not and rather than an empty array I get:
Array
(
[0] =>
[1] =>
[2] =>
[3] =>
)
This never registers as "empty". As far as I can tell I need the "else" syntax on there otherwise it fails.
Is there something else I can use besides NULL or FALSE? Or any other way to format it? I like this format because I have around 600 of these and it makes it much easier to read. Any suggestions?
You'll have to change the format as the check for existence needs to happen before you push another element onto the array. This should work:
if ($a->day_bed == 1) $sleeping[] = 'Day Bed';
You can save yourself lots of work by automating this task, eg like this
$bedTypes = array(
"day_bed" => "Day Bed",
"fold_up_bed" => "Fold up bed"
);
foreach ($bedTypes as $key=>$val) {
if ($a->{$key} == 1)
$sleeping[] = $val;
}
Another alternative is to use array_filter() with no callback to remove all falsy elements in the array:
<?php
$a = new stdClass();
$a->day_bed = false;
$a->fold_up_bed = false;
$a->murphy_bed = false;
$a->trundle_bed = false;
$sleeping[] = ($a->day_bed == 1) ? 'Day Bed' : false;
$sleeping[] = ($a->fold_up_bed == 1) ? 'Fold Up Bed' : false;
$sleeping[] = ($a->murphy_bed == 1) ? 'Murphy Bed' : false;
$sleeping[] = ($a->trundle_bed == 1) ? 'Trundle Bed' : false;
$emptySleeping = array_filter($sleeping);
if(empty($emptySleeping)) {
// here code if the array is empty.
}
var_dump($sleeping);
var_dump($emptySleeping);
See it in action

eval error when using "if" short form

when doing something like
$date = mktime();
$xxx = 'if ( date("N",$date ) == 1 ) { return TRUE; } else { return FALSE; }';
$yyy = eval( $xxx );
echo $yyy;
it works.
But when doing something like
$date = mktime();
$xxx = '( date("N",$date) == 1 ? return TRUE : return FALSE );';
$yyy = eval( $xxx );
echo $yyy;
I get an error like
Parse error: syntax error, unexpected T_RETURN in /my_path/my_file.php(107) : eval()'d code on line 1
Why ?
This has nothing at all to do with eval.
Let's create the real testcase:
<?php
function foo()
{
$date = mktime();
( date("N",$date) == 1 ? return TRUE : return FALSE );
}
foo();
?>
Output:
Parse error: syntax error, unexpected T_RETURN on line 5
return is a statement, not an expression, so you can't nest it into an expression which is what you're trying to do here. The conditional operator is not a one-line replacement for if/else.
To use the conditional operator properly:
return (date("N",$date) == 1 ? TRUE : FALSE);
which simplifies to just:
return (date("N",$date) == 1);
In your code, that looks like this:
$date = mktime();
$xxx = 'return (date("N",$date) == 1);';
$yyy = eval($xxx);
echo $yyy;
I'm pretty certain that should be
$xxx = 'return ( date("N",$date) == 1 ? TRUE : FALSE );';
The things generated by a ternary operator are values (expressions) rather than commands.

What is the most succinct way to test if either of two variables are set?

What I'm doing is, if I haven't got an ID in either $_POST or $_SESSION then redirecting. Preference is given to $_POST. So I have this:
$bool = 0;
if (isset($_POST['id'])) {
$bool = 1;
} elseif (isset($_SESSION['id'])) {
$bool = 1;
}
if (!$bool) {
...//redirect
}
Is there a quicker way to write this, APART from just removing the braces?
if(!( isset($_POST['id']) || isset($_SESSION['id']) ))
redirect();
(not sure if I understand how what's given to $_POST is preference).
You could just do:
$has_id = isset($_POST['id']) || isset($_SESSION['id']);
if (!$has_id) {
// redirect
}
(I'd recommend you to give your variables more descriptive names than just $bool.)
Although if you aren't using the variable for anything else, you could just do:
if (!isset($_POST['id']) && !isset($_SESSION['id'])) {
// redirect
}
if (isset($_POST['id']) || isset($_SESSION['id'])) {
$bool = 1;
}
This will do it, simples
$bool = (isset($_POST['id']) || isset($_SESSION['id'])) ? 1 : 0; // if isset, 1
($bool == 1?header(Location: www.whatever.com):null;
Using Conditional Operator, you can achieve this in one line statement
Example:
c = (a == b) ? d : e;

Categories