Xinchen Hui


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


strncmp doesn't supporting negative length:

   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:

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


base on feature request: , I wrote a patch to make strn(case)cmp supporting negative length,

after patched, following script:

   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:

var_dump(strncmp("prefix_num", "num", -10));
var_dump(strncmp("mun_xiferp", "mun", 10));
/** output:

BC Breaks

  • Any strncmp call with a computed length which may end up being negative will now potentially return a match where it wouldn't before.




Version Changed Date
7 Xinchen Hui: Initial RFC creation
6 Xinchen Hui: Updated patch to avoid making binary API changed
5 Xinchen Hui: Start voting
4 Xinchen Hui: Edited phpt
3 Xinchen Hui: Stop voting
2 Xinchen Hui: Open voting again, since there comes some new objections
1 Xinchen Hui: Won't apply now


An option needs 50%+1 votes to win

Do you want this feature in PHP 5.4 (68.8% approved)
User Vote
arpad Yes
cataphract Yes
derick No
felipe Yes
gwynne Yes
iliaa No
klaussilveira Yes
laruence Yes
levim No
pajoye Yes
pierrick Yes
rasmus No
rdohms Yes
salathe No
stas Yes
tyrael Yes