![]() ![]() However, you could always use $res = some_func() and then use $res in your if conditions - so you can avoid this problem alltogether.Ī case where you cannot use switch at all is when you have more complex conditions - switch only works for x = y with y being a constant value. It would be called twice - including possible side-effects of the function call happening twice. So, if the first case is case 0: and the second is case 'abc':, then the 'abc' is internally converted to the integer 0. ![]() two conditions.Ī case where switch actually gives you a performance advantage is if the variable part is a function call: switch(some_func()) Note that the datatype used for all case constants in a switch is determined by the first occurrence of a case, so all cases must use the same datatype, integer or string. Use true inside the switch and check in every case if the strpos() result is false. In this tutorial, I will show how to use switch and case with the strpos() function in PHP. In many cases, the switch statement may be a perfect fit for this. I'd also only use switch if there are more than e.g. Sometimes we need to check multiple strings for the presence of a specific piece of text. However, if all your conditions are of the type x = value with x being the same in every condition, switch usually makes sense. The reason I chose to use stristr () in this case is simply because it's case- insensitive, and thus, is more robust. You can use either stristr () or strstr (). PHP Switch Case Statement Examples December 18. 8 Answers Sorted by: 49 Based on this question and this answer, the solutions I've come up with ( while still using a case select) are below. When you want case insensitivity simply use stripos() instead. or switch is mainly a matter of preference. The strpos in the PHP Example function is used to find the first occurrence of a substring within the given string. The reason for using the identical operators (that also check for the type of the value) / is that strpos() might return 0 for a match at the beginning or false for no match which cannot be distinguished by or.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |