PHP converts a string to an integer (int) intval () printf () for performance testing

Source: Internet
Author: User
As early as a few years before SQL injection went viral, string conversion into integers has been listed as a required operation for every web program. The web program forcibly converts the id and integer equivalent values from get or post into integers through the conversion function, filters out dangerous characters, and minimizes the possibility of the system being injected by SQL. Background and overview
As early as a few years before SQL injection went viral, string conversion into integers has been listed as a required operation for every web program. The web program forcibly converts the id and integer equivalent values from get or post into integers through the conversion function, filters out dangerous characters, and minimizes the possibility of the system being injected by SQL.
Today, although SQL injection has gradually faded out of the historical stage, in order to ensure the normal operation of web programs, reduce the probability of errors, and better ensure the satisfaction of use, we also need to convert incorrect user input into what we need.
Conversion method
In PHP, we can convert a string to an integer in three ways.
1. forced type conversion
The forced type conversion method is the method of "adding the target type enclosed in brackets before the variable to be converted" (from the "type magic" section in the PHP Manual.
The code is as follows:
$ Foo = "1"; // $ foo is a string type.
$ Bar = (int) $ foo; // $ bar is an integer.
?>

For integer type, the forced conversion type is int or integer.
2. built-in function method
The built-in function method is to use the built-in function intval of PHP to convert variables.
The code is as follows:
$ Foo = "1"; // $ foo is a string type.
$ Bar = intval ($ foo); // $ bar is an integer.
?>

   The intval function format is:
Int intval (mixed $ var [, int $ base]); (from the PHP Manual)
Although the PHP Manual clearly states that intval () cannot be used for conversion between arrays and objects. However, after my tests, there will be no problem when converting the array. the conversion value is 1 instead of the expected 0. I'm afraid it is because the array type variables are considered non-zero in PHP. When converting an object, PHP will provide the following notice:
Object of class xxxx cocould not be converted to int in xxxxx. php on line xx
The conversion value is also 1.
3. format the string
The string format uses sprintf's % d to format the specified variable for type conversion.
The code is as follows:
$ Foo = "1"; // $ foo is a string type.
$ Bar = sprintf ("% d", $ foo); // $ bar is a string type.
?>

Strictly speaking, the sprintf conversion result is still 'string' type. Therefore, it should not be regarded as a string conversion to an integer. However, the string value after processing has indeed become "forcibly converted to an integer of the string type ".
Actual test
The above describes three methods for converting strings into integers in PHP. For general programmers, even if this is the end, the following part is for abnormal programmers.
1. test basic functions
Set the following array:
The code is as follows:
$ A [] = "1 ";
$ A [] = "a1 ";
$ A [] = "1a ";
$ A [] = "1a2 ";
$ A [] = "0 ";
$ A [] = array ('4', 2 );
$ A [] = "2.3 ";
$ A [] = "-1 ";
$ A [] = new Directory ();
?>

Convert the elements in the preceding array in three ways to view the conversion result. The program source code is as follows:
The code is as follows:
$ A [] = "1 ";
$ A [] = "a1 ";
$ A [] = "1a ";
$ A [] = "1a2 ";
$ A [] = "0 ";
$ A [] = array ('4', 2 );
$ A [] = "2.3 ";
$ A [] = "-1 ";
$ A [] = new Directory ();
// Int
Print "(int)
";
Foreach ($ a as $ v)
{
Var_dump (int) $ v );
Print"
";
}
// Intval
Print "intval ();
";
Foreach ($ a as $ v)
{
Var_dump (intval ($ v ));
Print"
";
}
// Sprintf
Print "sprintf ();
";
Foreach ($ a as $ v)
{
Var_dump (sprintf ("% d", $ v ));
Print"
";
}
?>

The final running result of the program is as follows (the notice generated when the object is converted has been removed ):
(Int)
Int (1)
Int (0)
Int (1)
Int (1)
Int (0)
Int (1)
Int (2)
Int (-1)
Int (1)
Intval ();
Int (1)
Int (0)
Int (1)
Int (1)
Int (0)
Int (1)
Int (2)
Int (-1)
Int (1)
Sprintf ();
String (1) "1"
String (1) "0"
String (1) "1"
String (1) "1"
String (1) "0"
String (1) "1"
String (1) "2"
String (2) "-1"
String (1) "1"
From this we can see that the three conversions have the same results. In terms of functions, all three methods can be used for conversion, so the next job is to see which one is more efficient.
2. performance testing
The tested string may be used in the injection process:
The code is as follows:
$ Foo = "1 '; Select *...";
?>
The function for obtaining the time point is as follows (used to obtain the test start point and end point to calculate the consumed time ):

**
* Simple function to replicate PHP 5 behaviour
*/
Function microtime_float ()
{
List ($ usec, $ sec) = explode ("", microtime ());
Return (float) $ usec + (float) $ sec );
}
?>

(From the microtime () function section of the PHP Manual)
The test procedure is to convert the variable $ foo 1000000 times (1 million times) in each method, and output the time consumption of each variable for a total of three groups of tests to minimize the error. The test procedure is as follows:
The code is as follows:
Function microtime_float ()
{
List ($ usec, $ sec) = explode ("", microtime ());
Return (float) $ usec + (float) $ sec );
}
$ Foo = "1 '; Select *...";

// (Int)
$ FStart = microtime_float ();
For ($ I = 0; I I <1000000; $ I ++)
{
$ Bar = (int) $ foo;
}
$ FEnd = microtime_float ();
Print "(int):". ($ fEnd-$ fStart). "s
";
// Intval ()
$ FStart = microtime_float ();
For ($ I = 0; I I <1000000; $ I ++)
{
$ Bar = intval ($ foo );
}
$ FEnd = microtime_float ();
Print "intval ():". ($ fEnd-$ fStart). "s
";
// Sprintf ()
$ FStart = microtime_float ();
For ($ I = 0; I I <1000000; $ I ++)
{
$ Bar = sprintf ("% d", $ foo );
}
$ FEnd = microtime_float ();
Print "sprintf ():". ($ fEnd-$ fStart). "s
";
?>

Final test result:
(Int): 0.67205619812012 s
Intval (): 1.1603000164032 s
Sprintf (): 2.1068270206451 s
(Int): 0.66051411628723 s
Intval (): 1.1493890285492 s
Sprintf (): 2.1008238792419 s
(Int): 0.66878795623779 s
Intval (): 1.1613430976868 s
Sprintf (): 2.0976209640503 s

Although this test is a little abnormal (who will continuously convert an integer of times ?), However, it can be seen that using forced type conversion to convert a string to an integer is the fastest.
Summary
Converting a string to an integer using the forced type conversion method is one of the most direct conversion methods (you can directly obtain the variable value of an integer ). From the perspective of code readability, the sprintf method has a long code, and the result may need to be forcibly converted again. The intval function is a typical process-oriented conversion, forced type conversion directly transmits the "I want to convert" idea to readers. In terms of efficiency, forced type conversion is also the fastest conversion method. Therefore, I recommend this method for programmers who often perform conversion work.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.