PHP: Short Ternary VS Null Coalescing Operator

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello guys today I want to show you quickly or remind you the difference between two PHP operators these ones so this is called ternary operator or short Syntax for ternary operator and this is called null coalescing operator and on the surface you can use both for example if querying eloquent model like this so show value or empty show value or empty and if we launch that in my Tinker well both are empty so does it mean they work the same way not exactly and I will show you the difference based on partially based on examples that I saw on Twitter by punya pal Shah so he had a tweet with different values I will demonstrate partially similar thing but in different order and with different variables so let's uncomment all of that and comment these ones so different variables a string number one true so basically something exists other group of variables false empty ring null and zero and also eloquent query which doesn't return any result so let's test the same thing on all those values and all those variables for each of the values one operator and another operator let's launch and see what happens and then I will comment the results so we launch and the results are pretty different aren't they so first they're kind of elephant in the room these values string 1 or true they both return as they should return the values so they are not empty any of those but then these ones behave a bit differently again we already saw that this one is identical would be empty and empty but then other ones false and all the other ones are empty if you use ternary operator but they are not empty if you use no coalescing operator and the answer is the name of the operator null coalescing operator so only in case of null it it actually returns this value so null or in the case of eloquent model for example value is also returning null so in other words this operator of ternary checks if the value is true or contains something some value otherwise it is empty in this case empty means only null so any other value 0 empty string false or any other value means not empty in other words not null and real practical examples of these depend on your application so I cannot show all of them but I hope this kind of reminder and comparison will give you some thought which one to use to show something in the blade file or assign the default value in controllers or models or whatever that's it for this short tip subscribe to the channel to get more daily ones and see you guys in other videos
Info
Channel: Laravel Daily
Views: 9,156
Rating: undefined out of 5
Keywords:
Id: POD1v1fqNyA
Channel Id: undefined
Length: 2min 56sec (176 seconds)
Published: Fri Jul 28 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.