Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ctype_space in PHP return "true" for some numeric values?

Tags:

php

I was recently playing with the ctype_* group of functions in PHP and found strange behaviour. For example, I have some code:

    for ( $i = 0; $i < 1000000; $i++ ) {
        if ( ctype_space( $i ) ) {
            var_dump( $i );
        }
    }

When $i has the values [9, 10, 11, 12, 13, 32] then [ctype_space][1] will return true. I am using the next PHP version:

   PHP 7.1.4-1+deb.sury.org~xenial+1 (cli) (built: Apr 11 2017 22:12:32) ( NTS )
   Copyright (c) 1997-2017 The PHP Group
   Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
      with Zend OPcache v7.1.4-1+deb.sury.org~xenial+1, Copyright (c) 1999-2017, by Zend Technologies
      with Xdebug v2.5.1, Copyright (c) 2002-2017, by Derick Rethans

Is this a bug or a feature of PHP? Maybe I don't know something? Please, help me to understand it.

like image 981
Kudryavtsev Maxim Avatar asked Dec 18 '22 07:12

Kudryavtsev Maxim


1 Answers

From the manual:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

In ASCII those numbers are whitespace characters:

 9 Horizontal tab
10 New Line
11 Vertical Tab
12 Form feed
13 Carriage return
32 Space
like image 131
John Conde Avatar answered Feb 01 '23 23:02

John Conde