130 of 410 menu

The strncmp Function

The strncmp function performs a binary-safe comparison of the first n characters of two strings, case-sensitively. Like strcmp, it returns 0 if they are equal, a negative number if the first string is less, and a positive number if it is greater.

Syntax

strncmp(string $str1, string $str2, int $length): int

Example

Comparing the first 3 characters of identical strings:

<?php $res = strncmp("Hello", "Help me", 3); echo $res; ?>

Code execution result:

0

Example

Comparing the first 4 characters of different strings:

<?php $res = strncmp("apple", "apricot", 4); echo $res; ?>

Code execution result (negative number, because 'l' < 'r'):

-8

Example

Checking a string prefix:

<?php $url = "https://example.com"; if (strncmp($url, "https://", 8) === 0) { echo "Secure connection"; } ?>

Code execution result:

"Secure connection"

See Also

  • the strcmp function,
    which compares strings in their entirety
  • the strncasecmp function,
    which compares the first n characters case-insensitively
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline