Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a parameter to return the string strstr if it doesn't find it?

as the title indicates, I am currently using a strstr to trim strings like this

$destino = "Piura - Lima";
echo strstr($destino, ' - ', true)
Result: Piura

But if it doesn’t find the value the strstr returns a null value
Example

$destino = "Piura * Lima";
echo strstr($destino, ' - ', true)
Result: NULL

Is there any parameter/option to return the value of $destino if it doesn’t find the match?
Maybe something similar that will do the result?
Anything goes but I prefer to use strstr.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Note: I know this can be fixed with a simple IF but I want as minimal as possible.

>Solution :

You can use the empty ternary operator (also sometimes called the Elvis operator) to default back to your original value in this case:

$destino = "Piura * Lima";
$value = strstr($destino, ' - ', true) ?: $destino;
var_dump($value);

Output:

string(12) "Piura * Lima"

This is basically the same as:

$value = strstr($destino, ' - ', true);
if ($value === false) {
    $value = $destino;
}

Note that strstr() returns FALSE here, and not NULL.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading