Current Location: Home> Latest Articles> Construct concise judgment using stripos and ternary operators

Construct concise judgment using stripos and ternary operators

M66 2025-06-02

In PHP programming, processing strings and implementing conditional judgments are very common tasks. This article will introduce two utility tools: stripos functions and ternary operators, and show how they can be used in combination to write concise and efficient code.

What is stripos?

stripos is a function in PHP to find the first occurrence of a certain segment string in a string. Unlike strpos , strpos is case-insensitive .

grammar:

 stripos(string $haystack, mixed $needle, int $offset = 0): int|false
  • $haystack : The main string to search for.

  • $needle : The substring to be found.

  • $offset : Optional parameter, specifying where to start the search.

If a substring is found, stripos returns its first occurrence position (starting at 0), and if it is not found, false .

What is a ternary operator?

The ternary operator is a concise way of writing if...else , in the form as follows:

 condition ? expression1 : expression2;

Returns expression 1 when the condition is true ; otherwise returns expression 2.

stripos + ternary operator: practical example

We can use stripos and ternary operators to achieve concise string judgment logic. For example, determine whether a URL contains the keyword login :

 <?php
$url = "https://m66.net/user/login";

echo (stripos($url, 'login') !== false) 
    ? "This is a login page。" 
    : "This is not a login page。";
?>

Output result:

 This is a login page。

Here we use stripos($url, 'login') !== false to determine whether $url contains login , and then use the ternary operator to output different content based on the judgment result.

Further applications

Suppose you want to determine whether the visitor comes from a subdomain and output a welcome message according to different situations: