php - Check if last character is "s" or "z"
Get the solution ↓↓↓is there a more gallant way to check if last character is "s" or "z" than:
if (substr($var, -1, 1) == "s" OR substr($var, -1, 1) == "z") ...
Something like
if (substr($var, -1, 1) == "s" OR "z") ...
would be nice, but is there something like this in PHP?
Answer
Solution:
Usein_array
and looking for last character in array:
if (in_array(substr($var, -1, 1), ['s', 'z']))
Answer
Solution:
Or maybe:
in_array(array_pop(explode('', $var)), ['s', 'z'])` ?
not really much more readable neither gallant, but what do I know? :)
Answer
Solution:
Tired of code that's too easy to understand? Regular expressions to the rescue:
preg_match('/[sz]$/', $var)
Answer
Solution:
If you are able to use PHP8, then you should this simple solution available in PHP8.
https://www.php.net/manual/en/function.str-ends-with.php
<?php
$text = 'foods';
if (str_ends_with($text, 's') || str_ends_with($text, 'z')) { ... }
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: an exception occurred in the driver: could not find driver
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.