Php if var like

How exactly does if($variable) work? [duplicate]

I’ve seen it used in scripts several times, and now I really want to know what it «looks for». It’s not missing anything; it’s just a plain variable inside an if statement. I couldn’t find any results about this, anywhere, so obviously I’ll look stupid posting this.

8 Answers 8

The construct if ($variable) tests to see if $variable evaluates to any «truthy» value. It can be a boolean TRUE , or a non-empty, non-NULL value, or non-zero number. Have a look at the list of boolean evaluations in the PHP docs.

From the PHP documentation:

var_dump((bool) ""); // bool(false) var_dump((bool) 1); // bool(true) var_dump((bool) -2); // bool(true) var_dump((bool) "foo"); // bool(true) var_dump((bool) 2.3e5); // bool(true) var_dump((bool) array(12)); // bool(true) var_dump((bool) array()); // bool(false) var_dump((bool) "false"); // bool(true) 

Note however that if ($variable) is not appropriate to use when testing if a variable or array key has been initialized. If it the variable or array key does not yet exist, this would result in an E_NOTICE Undefined variable $variable .

@BasilMusa No, it should not be used to check if variables have been initialized. It would cause E_NOTICE undefined variable $var if the variable was not yet initialized. You must use isset($var) to know if they’ve been initialized, and then check its boolean value.

One can also use !empty($var) to check for both variable being set and being «truthy». In php7 there is a shorthand operand ?? for it, so: $isSetAndTruthy = $var ?? false; is equal to $isSetAndTruthy = !empty($var); and is equal to $isSetAndTruthy = isset($var) && $var;

If converts $variable to a boolean, and acts according to the result of that conversion.

See the boolean docs for further information.

To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.

The following list explains what is considered to evaluate to false in PHP:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string «0»
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource).

In your question, a variable is evaluated inside the if() statement. If the variable is unset, it will evaluate to false according to the list above. If it is set, or has a value, it will evaluate to true, therefore executing the code inside the if() branch.

It checks whether $variable evaluates to true . There are a couple of normal values that evaluate to true , see the PHP type comparison tables.

if ( ) can contain any expression that ultimately evaluates to true or false .

if (true) // very direct if (true == true) // true == true evaluates to true if (true || true && true) // boils down to true $foo = true; if ($foo) // direct true if ($foo == true) // you get the idea. 

Any of these are considered to be false (so that //code to be executed would not run)

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string «0»
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags
Читайте также:  Html javascript объект форма

All other values should be true. More info at the PHP Booleans manual.

Try looking at this old extended «php truth table» to get your head around all the various potholes waiting to burst your tyres. When starting out be as explicit as you can with any comparison operator that fork your code. Try and test against things being identical rather that equal to.

It depends entirely on the value type of the object that you are checking against. In PHP each object type has a certain value that will return false if checked against. The explanation of these can be found here: http://php.net/manual/en/language.types.boolean.php Some values that evaluate to false are

object: object has 0 properties / is empty

Its a bit different from most other languages but once you get used to it it can be very handy. This is why you may see a lot of statements such as

$result = mysqli_multi_query($query) or die('Could not execute query'); 

A function in PHP need only return a value type that evaluates to false for something like this to work. The OR operator in PHP will not evaluated its second argument IF the first argument is true (as regardless of the second argument’s output, the or statement will still pass) and lines like this will attempt to call a query and assign the result to $result. If the query fails and the function returns a false value, then the thread is killed and ‘Could not execute query’ is printed.

Источник

Php if variable like string

Instead of my original solution I was trying to attempt, I created a new content type within the CMS and wrote my modifications for that content type only. Solution 2: You should cast to a string: The following is from php docs: Which means you were comparing «253,254,255» with the character corresponding to 253 in the ASCII table Solution 3: You need to cast the integer to a string.

PHP Conditional to see if string contains a variable [duplicate]

I’m struggling to figure out how to use PHP strpos to find a variable in a string. The code below works if I enter a number directly but not if I replace the number with a variable I know to be a single number. No PHP errors present but the conditional renders false. I’ve been searching all over and am stumped by this.

The $string variable returns «253,254,255».

The $current_page_id variable returns «253».

 $string = ""; foreach( $page_capabilities as $post): $string .= $post->ID.','; endforeach; if (strpos($string, $current_page_id) !== false) < // This works //if (strpos($string, '253') !== false) < // This does not if (strpos($string, $current_page_id) !== false) < echo 'true'; >> 

You don’t need that CSV string to check for the ID you’re looking for. You can just do it in the foreach loop where you’re currently building the string.

foreach ($page_capabilities as $post) < if ($post->ID == $current_page_id) < echo 'true'; break; // stop looking if you find it >> 

You should cast $current_page_id to a string:

if (strpos($string, (string)$current_page_id) !== false) < . 

The following is from php docs:

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Which means you were comparing "253,254,255" with the character corresponding to 253 in the ASCII table

Читайте также:  Python pyodbc insert into

You need to cast the integer to a string.

$postIDs = [55, 89, 144, 233]; $string = implode(',', $postIDs); $postID = 55; if(strpos($string, strval($postID)) !== false)

I would suggest you to change your approach. You should search for the exact string value. Because as @mickmackusa suggested, it would find 25 & 53 too

 $page_capabilities = array(array('POSTID' => 253),array('POSTID' => 254),array('POSTID' => 255)); $current_page_id = '255'; $key = array_search($current_page_id, array_column($page_capabilities, 'POSTID')); if($key !== false)

Check if string contains a value in array [duplicate], Try this. $string = 'my domain name is website3.com'; foreach ($owned_urls as $url) < //if (strstr($string, $url)) < // mine version if (strpos($string,

PHP if variable contains string or multiple words

I have these two variables

$page_title = '[[+pagetitle]]'; $title_match = 'Marketing Campaign Calendar'; 

The first is pulling the name of an asset or page and the second are three words I want to search for within those titles. I currently have this if statement which works perfectly as is but I need to add another condition.

if(in_array($content_name, $open_modal_types)) < // Return view / download buttons return '
View Download
'; > else if($is_binary == '1') < // Return download button return 'Download'; >

So I'm trying to accomplish something like this:

if(in_array($content_name, $open_modal_types)) < // Return view / download buttons if($page_title contains all of the words in $title_match) < return "something"; >else< return '
View Download
'; > > else if($is_binary == '1') < // Return download button return 'Download'; >

I've tried using strpos and preg_match but couldn't get it to work. I don't know if I have too many if statements or what. Any suggestions will be helpful. Thanks

You can use a function like this

 > return true; // if we got here, it contains all the words > var_dump(containsAllWords("test1 test2 test4", $words)); // false var_dump(containsAllWords("test1 test2 test3 test4", $words)); // true 
if($page_title contains all of the words in $title_match) 
$title_match = '('.str_replace(' ',')&(', $title_match).')'; if(preg_match('/'.$title_match.'/i', $title_match)) 

But you should be sure that $title_match not contains special symbols, or filter it by \

So the site I am working on is built in Modx which is fairly new to me. Instead of my original solution I was trying to attempt, I created a new content type within the CMS and wrote my modifications for that content type only. This makes much better sense than what I was trying to do before. Any other Modx users out there, feel free to reach out to me if you want more details on my solution and what I was trying accomplish.

Thanks to those for trying to help.

PHP/SQL if variable contains string which is the same as x, You can do something like this: $dates = str_replace(PHP_EOL, "','", trim($data)); $query_overeenkomst = "SELECT * from $stad WHERE

Compare first 4 characters of a string PHP

The problem is with this line:

and I'm not sure how to fix it. Thanks.

You need PHP not MySQL. For 1800% just check that it is found at position 0 :

If it can occur anywhere like %1800% then:

if(strpos($var, '1800') !== false) < //stop the code exit; >else

Use substr function to get first 4 characters and compare it with 1800 .

Another way could be to use strpos()

I would use a regular expression for this preg_match('/^1800.+/', $search, $matches);

PHP string "contains" [duplicate], Note that you need to use the !== operator. If you use != or <> and the '.' is found at position 0 , the

Источник

Assign variable within condition if true

I know you can assign a variable in a condition like this: if ($var = $foo) However I don't need to do anything in the condition itself, so I'm often left with empty brackets. Can I simply assign $var if $foo is true in some other way without needing to do something else later? Also can I assign $var to $foo if $foo is true but if $foo is false do something else? Like:

You're not assigning "in the condition". You're assigning regardless of the value of $foo . So if you only want to overwrite $var with $foo in case $foo is truthy. You'll have to move the assignment. Or do something like if ($foo && $var = $foo) <> though the latter is really awful in my opinion.

@Yoshi My issue is more what happens after the value of $var has been assigned. So if it failed to assign, have a fallback. The answers demonstrate what I was trying to do. Thanks for your comment.

4 Answers 4

@chandresh_cool's suggestion is right but to allow multiple possiblities / fallbacks you would have to nest the ternary expressions:

$var = ($foo == true) ? $foo: ($bar == true) ? $bar: ($fuzz == true) ? $fuzz: $default; 

Note: the first 3 lines end in colons not semi-colons.

However a simpler solution is to do the following:

Your simpler solution is exactly what I'm looking for. It's short, sweet and does what I need it to do: set $var to the first positive value it can find.

Although this is a very old post. Fallback logic on falsify values can be coded like this.

In this case when $foo is a falsified value (like false, empty string, etc.) it will fall back to $bar otherwise it uses $foo . If bar is a falsified value, it will fallback to the string default .

Keep in mind, that this works with falsified values, and not only true .

$foo = ""; $bar = null; $var = $foo ?: $bar ?: "default"; 

$var will contain the text default because empty strings and null are considered "false" values.

In php 7 you can use the new null coalescing operator: ?? , which also checks if the variable exists with isset(). This is usefull for when you are using a key in an array.

$array = []; $bar = null; $var = $array['foo'] ?? $bar ?? "default"; 

Before php 7 this would have given an Undefined index: foo notice. But with the null coalescing operator, that notice won't come up.

Источник

Оцените статью