- Check if variable is set and then echo it without repeating?
- 3 Answers 3
- What is the PHP shorthand for: print var if var exist
- 11 Answers 11
- For PHP >= 7.0:
- For PHP >= 5.x:
- Check if Variable exists and === true
- 4 Answers 4
- If you want it in a single statement:
- If you want it in a single condition:
- How to check if a string contains a specific text [duplicate]
- 6 Answers 6
- Check if exists or not in the same line PHP
- 2 Answers 2
- Related
- Hot Network Questions
- Subscribe to RSS
Check if variable is set and then echo it without repeating?
Is there a concise way to check if a variable is set, and then echo it without repeating the same variable name? Instead of this:
PHP has sprintf, but it doesn’t quite do what I was hoping for. If course I could make a method/function out of it, but surely there must be a way to do it «natively»? Update: Ternary operations would also repeat the $this->variable part, if I understood it?
I’m not aware of any shorthand for that. If you use it a lot, I would anyway recommend creating a function for that.
3 Answers 3
The closest you can get to what you are looking for is using short form of ternary operator (available since PHP5.3)
echo $a ?: "not set"; // will print $a if $a evaluates to `true` or "not set" if not
But this will trigger «Undefined variable» notice. Which you can obviously suppress with @
Still, not the most elegant/clean solution.
So, the cleanest code you can hope for is
Here is the example from php.net.
For those not using PHP7 yet here is my original answer.
I use a small function to achieve this:
$a = 'potato'; echo ifset($a); // outputs 'potato' echo ifset($a, 'carrot'); // outputs 'potato' echo ifset($b); // outputs nothing echo ifset($b, 'carrot'); // outputs 'carrot'
Caveat: As Inigo pointed out in a comment below one undesirable side effect of using this function is that it can modify the object / array that you are inspecting. For example:
$fruits = new stdClass; $fruits->lemon = 'sour'; echo ifset($fruits->peach); var_dump($fruits);
(object) array( 'lemon' => 'sour', 'peach' => NULL, )
What is the PHP shorthand for: print var if var exist
We’ve all encountered it before, needing to print a variable in an input field but not knowing for sure whether the var is set, like this. Basically this is to avoid an e_warning.
without making a function for it I think @Marc B has provided the shortest way to do it. in a comment no less!
11 Answers 11
For PHP >= 7.0:
As of PHP 7 you can use the null-coalesce operator:
For PHP >= 5.x:
My recommendation would be to create a issetor function:
function issetor(&$var, $default = null)
This takes a variable as argument and returns it, if it exists, or a default value, if it doesn’t. Now you can do:
But also use it in other cases:
$user = issetor($_GET['user'], 'guest');
Why are you doing a call by reference? Isn’t value enough? Also, default is a keyword in PHP, it might be wise to not use that as a function name. It had weird results on my server.
@afuzzyllama: Because I need to pass a potentially undefined variable. If I left out the reference it would give you a Undefined Variable Notice 😉
@afuzzyllama: Thanks for pointing out, renamed it to issetor (I think that’s how they named it, when they wanted to implement it in PHP 6, but I’m not quite sure.)
One thing about this method — calling issetor as issetor($var[‘key’]) will inject key into $var . In some cases, you might end up with unexpected behavior, particularly if you’re iterating over keys later.
Not a big fan of this. PHP should throw an undefined variable warning when you pass it by reference as well.
The shortest answer I can come up with is
A simple alternative to an if statement, which is almost like a ternary operator, is the use of AND. Consider the following:
This does not work with echo() for some reason. I find this extremely useful!
Better use a proper template engine — https://stackoverflow.com/q/3694801/298479 mentions two nice ones.
Here’s your function anyway — it will only work if the var exists in the global scope:
It’s dirty if it’s suppressing an actual error. Is it really worth it to spend the time, or increase the complexity of the code when a simpler solution will suffice? As long as you are aware of what you are doing, and why the warning is being suppressed this is fine.
There can be no errors in printing or echoing a variable. If the variable doesnt exist, it wont print. If there is something to print, php will take care for it. arychj is right.
@demian / thief: I’d agree if it was to supress a function’s error, but frankly, supressing the «not defined» warning on a variable in an output situation is allowable
@mella: in some cases you don’t have that level of control of the server, which is where the usual «ZOMG DON’T EVER USE SHORTTTAGS! THEY ARE TEH BAD. » breathelessly panicky warnings come from.
@Marc B: Logically I agree, however, if someone more junior than you reads the code and says «ohh it’s okay to use suppression», I guarantee you’ll find it littered throughout the rest of the code that they write 🙂 I think the overhead of writing in an isset or empty is much more preferable than bad habits 🙂
@demian: that’s like saying we shouldn’t have knives in the kitchen for dinner prep because they can be used to stab people in back alleys. Appropriate tools for appropriate jobs, and in the cases where you can’t disable the warnings, suppression is the best bet, unless you want gunk up your code with repeated echo (isset($var) ? $var : ») constructs.
There’s currently nothing in PHP that can do this, and you can’t really write a function in PHP to do it either. You could do the following to achieve your goal, but it also has the side effect of defining the variable if it doesn’t exist:
function printvar(&$variable) < if (isset($variable)) < echo $variable; >>
This will allow you to do printvar($foo) or printvar($array[‘foo’][‘bar’]) . However, the best way to do it IMO is to use isset every time. I know it’s annoying but there’s not any good ways around it. Using @ isn’t recommended.
Check if Variable exists and === true
Checking if === would do the trick but a PHP notice is thrown. Do I really have to check if the field is set and then if it is true?
4 Answers 4
If you want it in a single statement:
If you want it in a single condition:
Well, you could ignore the notice (aka remove it from display using the error_reporting() function).
Or you could suppress it with the evil @ character:
This solution is NOT RECOMMENDED
I think this should do the trick .
if( !empty( $arr['field'] ) && $arr['field'] === true )
I think the point is kinda have it in a single condition. But maybe that’s what he meant and I misunderstood.
He said one IF statement, that is one. Having && doesn’t make it two, does it? If so, then I guess I was wrong. Didn’t come to what you replied tho’, clever 🙂
My problem was that the notice was thrown when I checked in a single statement. But the @ will Do the trick I think. I thought I was doing something wrong :-/
empty() and inset() respectively will take that error away, well at least it does for me. However @ is shorter and sweeter indeed. Best of luck for you future ventures 🙂
echo isItSetAndTrue('foo', array('foo' => true))."
\n"; echo isItSetAndTrue('foo', array('foo' => 'hello'))."
\n"; echo isItSetAndTrue('foo', array('bar' => true))."
\n"; function isItSetAndTrue($field = '', $a = array())
it is set and has a true value it is set but not true does not exist
Alternative Syntax as well:
$field = 'foo'; $array = array( 'foo' => true, 'bar' => true, 'hello' => 'world', ); if(isItSetAndTrue($field, $array)) < echo "Array index: ".$field." is set and has a true value
\n"; > function isItSetAndTrue($field = '', $a = array())
Array index: foo is set and has a true value
How to check if a string contains a specific text [duplicate]
If you are checking the string if it has any text then this should work if(strlen($a) > 0) echo ‘text’; or if your concern is to check for specific word the follow the @Dai answer.
6 Answers 6
$haystack = "foo bar baz"; $needle = "bar"; if( strpos( $haystack, $needle ) !== false)
if( strpos( $a, 'some text' ) !== false ) echo 'text';
Note that my use of the !== operator (instead of != false or == true or even just if( strpos( . ) ) < ) is because of the "truthy"/"falsy" nature of PHP's handling of the return value of strpos .
As of PHP 8.0.0 you can now use str_contains
@Blender sorry, you’re right. I was thinking of the .NET String.IndexOf which returns -1 in event of a non-match. I’ve corrected my answer.
@PadronizaçãoSA The ! operator will affect the falsiness of the return value from strpos which means === won’t work the way it’s intended.
Empty strings are falsey, so you can just write:
Although if you’re asking if a particular substring exists in that string, you can use strpos() to do that:
if (strpos($a, 'some text') !== false)
http://php.net/manual/en/function.strpos.php I think you are wondiner if ‘some text’ exists in the string right?
if(strpos( $a , 'some text' ) !== false)
If you need to know if a word exists in a string you can use this. As it is not clear from your question if you just want to know if the variable is a string or not. Where ‘word’ is the word you are searching in the string.
or use the is_string method. Whichs returns true or false on the given variable.
Check if exists or not in the same line PHP
I want to check a values of : type1,type2 and type3 if it it exists if not return 0 in the same line.
2 Answers 2
PHP 7 introduces the so called null coalescing operator which simplifies the statements to:
So, your code would become
You can use the ternary operator as followed. Note you don’t need to wrap the array in ‘[]’
If you want to check all are set you could use;
To simplify further as suggested by Magnus Eriksson:
If you wish to check for just one use the or/double pipe || expression
I think it should return $a[‘type1’] , not $a[‘type2’] , since it is the first you’re checking if it is set.
that would make sense. However type2 was the OP original question. Maybe he wants to check type two as well?
You’re second example could be even simpler by passing all variables in the same isset: isset($a[‘type1’], $a[‘type2’], $a[‘type3’]) . That’s the same thing as having three isset() in a row.
This question is in a collective: a subcommunity defined by tags with relevant content and experts.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.20.43540
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.