Table of Contents

RFC: strn(case)cmp supporting a negative length as its third paramter

Introduction

strncmp doesn't supporting negative length:

<?php
   if (strncmp("prefix_num", "num", -3) === 0) {
        echo "they have same suffix\n";
   }
?> 

running the above script in PHP 5.3.6 will result:

warning: Length must be greater than or equal to 0 in /tmp/1.php 

We need to write some codes like following one to make it works as expect:

<?php
   if (strncmp(substr("prefix_num", -3, 3), "num", 3) === 0) {
        echo "they have same suffix\n";
   }
?> 

Proposal

base on feature request: https://bugs.php.net/bug.php?id=36944 , I wrote a patch to make strn(case)cmp supporting negative length,

after patched, following script:

<?php
   if (strncmp("prefix_num", "num", -3) === 0) {
        echo "they have same suffix\n";
   }
?> 

will work as expect.

and if the abs of the negative length is greater than any strlen of the first two parameters, then strn(case)cmp will work as strncmp in the reverse order with the abs value:

<?php
var_dump(strncmp("prefix_num", "num", -10));
var_dump(strncmp("mun_xiferp", "mun", 10));
/** output:
int(7)
int(7)
*/
?> 

BC Breaks

Patches

Tests

Vote

Do you want this feature in PHP 5.4
Real name yes no
arpad (arpad)  
cataphract (cataphract)  
derick (derick)  
felipe (felipe)  
gwynne (gwynne)  
iliaa (iliaa)  
klaussilveira (klaussilveira)  
laruence (laruence)  
levim (levim)  
pajoye (pajoye)  
pierrick (pierrick)  
rasmus (rasmus)  
rdohms (rdohms)  
salathe (salathe)  
stas (stas)  
tyrael (tyrael)  
Count: 11 5

Changelog