PHP strncmp Function: Binary‑Safe String Comparison

The article explains PHP's strncmp function, a binary‑safe, case‑sensitive string comparison that compares the first N characters of two strings, detailing its syntax, parameters, return values, and providing practical code examples with expected outputs.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP strncmp Function: Binary‑Safe String Comparison

Function: int strncmp(string $str1, string $str2, int $len) – binary‑safe comparison of the beginning of two strings up to a specified length.

Description: The function works like strcmp() but allows you to limit the number of characters compared. It is case‑sensitive.

Parameters: $str1: first string. $str2: second string. $len: maximum number of characters to compare.

Return value: Returns <0 if $str1 is less than $str2, >0 if greater, and 0 if they are equal within the specified length.

Example 1:

<?php
    echo strncmp("Hello world!", "Hello earth!", 6);
?>

Output: // 0 Example 2:

<?php
echo strncmp("Hello", "Hello", 6);
echo "<br>";
echo strncmp("Hello", "hELLo", 6);
?>

Output:

// 0
// -1
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentPHPstring-comparisonbinary safestrncmp
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.