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 - strcmp

Trieda

Koreň \ Bez triedy

Metóda - strcmp

(PHP 4, PHP 5, PHP 7)

The strcmp() function compares two strings binary. 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 strcmp (string $str1, string $str2) : int

Parametre

NázovDátový typPredvolená hodnotaPopis
$str1string

The first string for comparing.

$str2string

The second string for comparing.

Mávratovej hodnoty

Vracia: int

Returns 0 if both strings are equal. 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 parameters is an array/object.

Príklady

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

<?php
var_dump(strcmp('hello world', 'Hello World'));     // int(32)
var_dump(strcmp('Hello World', 'hello world'));     // int(-32)
var_dump(strcmp('Hello World', 'Hello World'));     // int(0)
var_dump(strcmp('hello', 'hello world'));           // int(-6)
var_dump(strcmp('hello world', 'hello'));           // int(6)

Now let's try to give other parameters than only strings:

<?php
var_dump(strcmp('Hello World', null));      // int(11)
var_dump(strcmp('Hello World', false));     // int(11)
var_dump(strcmp(false, 'Hello World'));     // int(-11)
var_dump(strcmp(array('hello', 'world'), 'Hello World'));   // Emits a warning and returns NULL
var_dump(strcmp('Hello World', 0));         // int(24)
var_dump(strcmp(0, 'hello world'));         // int(-56)
var_dump(strcmp(false, 0));                 // int(-1)
var_dump(strcmp(0, -1));                    // int(3)
var_dump(strcmp(0, 1));                     // int(-1)
var_dump(strcmp(300, 200));                 // int(1)

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 strncmp (string $str1, string $str2, int $len) : int
      • function strstr (string $haystack, mixed $needle, bool $before_needle = false) : string
      • function substr (string $string, int $start, int $length) : string
      Aktivity