0

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?

Philip
  • 1,068
  • 3
  • 12
  • 21
  • 1
    Does this answer your question? [Simpler way to check if variable is not equal to multiple string values?](https://stackoverflow.com/questions/19949923/simpler-way-to-check-if-variable-is-not-equal-to-multiple-string-values) – Progman Mar 06 '21 at 21:55

4 Answers4

2

Use in_array and looking for last character in array:

if (in_array(substr($var, -1, 1), ['s', 'z']))
Lessmore
  • 1,061
  • 1
  • 8
  • 12
1

Or maybe:

in_array(array_pop(explode('', $var)), ['s', 'z'])` ?

not really much more readable neither gallant, but what do I know? :)

entio
  • 3,816
  • 1
  • 24
  • 39
0

Tired of code that's too easy to understand? Regular expressions to the rescue:

preg_match('/[sz]$/', $var)
  • Haha nice. Well, programming is not my job so I don't know what would be the state of the art. Would you rather choose my original solution as it is more readable? – Philip Mar 07 '21 at 16:24
  • I'm mostly a C++ programmer, so I view "that's clever" as a curse. Clarity and readability over cleverness. If you know regular expressions, this one is fairly clear, `[]` is "one of" and `$` is "end of string", if you don't, I wouldn't recommend it. –  Mar 07 '21 at 17:36
  • I do but I figured that a regular expression would be a little bit too over-engineered and also slower, as a regular expression in general takes longer, right? – Philip Mar 08 '21 at 23:50
0

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')) { ... }