Hướng dẫn php if else shorthand
I have a string that I want to append it some other string. let's say:
this would return 'Hello there'. I want to make this conditional like this:
Now, I want to use a ternary operation to do this, but all the examples I came across are for if/else which will be something like:
so is it possible to do it with only IF and without else? Jason Aller 3,48128 gold badges40 silver badges37 bronze badges asked Jun 22, 2011 at 23:09 3 Nope. However, the opposite is possible. Here's a quote from the PHP docs:
http://php.net/manual/en/language.operators.comparison.php answered Jun 22, 2011 at 23:16 AndzAndz 2,18616 silver badges12 bronze badges No... ternary means three parts you need the condition, the true part, and the false part answered Jun 22, 2011 at 23:12 BuellerBueller 2,28017 silver badges11 bronze badges 0 combining mellamokb and Andz you can do this:
answered Jun 22, 2011 at 23:21 Jacob EggersJacob Eggers 8,8722 gold badges23 silver badges40 bronze badges 2 An alternative way to check for a condition and then append to the string would be:
But that's really just an answered Jun 22, 2011 at 23:39 mariomario 142k20 gold badges236 silver badges285 bronze badges 4 You can do this:
If you invert the statement so that the ternary is on the outside instead of the inside of the assignment, then you can put an entire statement in the TRUE part, then just do something that is a no-operation command in the ELSE part. answered Jun 22, 2011 at 23:19 mellamokbmellamokb 55.4k12 gold badges106 silver badges135 bronze badges if you are considering to make the code shorter you can write the same thing on a single line.
EDIT I just discovered this and thought come in handy. You can also write the if block like this
answered Mar 15, 2013 at 6:19 astroanuastroanu 3,8172 gold badges35 silver badges50 bronze badges 0 You cannot use the ternary without the else/false part, but if your purpose is to have everything on one line I could suggest to try this alternative:
If the first one is true it will proceed with the second statement. Otherwise will just stop after the first evaluation resulting false. Refer to the lazy evaluation (the so called Short-circuit evaluation) Or you can do the opposite, leaving the true if part empty, and declare just the false, as Andz correctly points to. answered Aug 24, 2014 at 17:45 KamafeatherKamafeather 7,51513 gold badges56 silver badges89 bronze badges You could create a function that does what you want. Instead of writing out
the
Call it with:
Note how the second parameter is by reference, so it will be changed in the calling code too. answered Jun 22, 2011 at 23:27 zsalzbankzsalzbank 9,5251 gold badge24 silver badges39 bronze badges a simple an very effective way could be to use
Tim Diekmann 7,04310 gold badges36 silver badges59 bronze badges answered Aug 7, 2018 at 8:22 |