NOVINKA: Najžiadanejšie rekvalifikačné kurzy teraz s 50% zľavou + kurz AI ZADARMO. Nečakaj, táto ponuka dlho nevydrží! Zisti viac:

PHP - strncmp

Trieda

Koreň \ Bez triedy

Metóda - strncmp

(PHP 4, PHP 5, PHP 7)

The strncmp() function compares two strings up to the given length. The function is `case sensitive and binary safe.

The first two parameters must be strings, otherwise the function can return misleading results.

Procedurálne

  • function strncmp (string $str1, string $str2, int $len) : int

Parametre

NázovDátový typPredvolená hodnotaPopis
$str1string

The first string for comparing.

$str2string

The second string for comparing.

$lenint

The number of characters to be compared in both strings.

Mávratovej hodnoty

Vracia: int

Returns 0 if both strings are equal up to the specified length, or if the last parameter is 0. If the first string is greater than the second one, returns a positive number, otherwise returns a negative number.

The result also can be null if one of the first two parameters is an array/object, or false if the last parameter is smaller than 0.

Príklady

Let's try to compare 2 strings at first and notice the difference between lower-case and upper-case letters:

<?php
var_dump(strncmp('hello', 'hello world', 5));       // int(0)
var_dump(strncmp('hello', 'hello world', -1));      // Emits a warning and returns FALSE
var_dump(strncmp('different', 'strings', 0));       // int(0)
var_dump(strncmp('Hello World', 'hello world', 5)); // int(-32)
var_dump(strncmp('world', 'hello world', 5));       // int(15)

var_dump(strncmp('hello world', 'hello world', 11));    // int(0)
var_dump(strncmp('hello world', 'hello world', 27));    // int(0)

We can see that if the length exceeds the length of both strings, the result will be the same.

Now let's try to pass other parameter types than strings:

<?php
var_dump(strncmp(false, 'hello world', 1));     // int(-1)
var_dump(strncmp(false, 'hello world', 11));    // int(-11)
var_dump(strncmp(array('hello', 'world'), 'hello world', 5));   // Emits a warning and returns NULL
var_dump(strncmp(100, 300, 1));                 // int(-2)
var_dump(strncmp(100, 300, 5));                 // int(-2)

We can see the results are very misleading in some cases.

Súvisiace manuály

      • function preg_match (string $pattern, string $subject, array &$matches, int $flags = 0, int $offset = 0) : int
      • function strcmp (string $str1, string $str2) : int
      • function strstr (string $haystack, mixed $needle, bool $before_needle = false) : string
      • function substr (string $string, int $start, int $length) : string
      Aktivity