I was recently working on a pull request where I wanted to take an array of object IDs and convert that into a string to be used in a SQL statement.
But, to prevent potential issues such as SQL injection, I needed to find a way to sanitize the array of integers and make sure that we only had integers in the array. Here is the solution that I used.
// Sanitize so that the array only has integer values.
$sanitized_array = array_map( 'intval', $ids );
// Now that we have all integers in our array, we can safely implode the
// array to be used in a SQL statement.
$ids_string = implode( ', ', $sanitized_array );
$sql = "SELECT * FROM {$table} WHERE {$object_id_column} IN ( {$ids_string} ) AND meta_key = %s";
If you’re not used to mapping an array of values, you may be wondering what the heck array_map()
is doing. What array_map() does is iterate over an array (the second argument) and apply a callback function (the first argument) to each value in the array.
We then get back the resulting array with each value being sanitized by intval()
.
Alternative solution to sanitizing an array of integers
If you’re still a bit confused about what array_map( 'intval', $ids )
, here’s another way to approach the issue:
// Sanitize so that the array only has integer values.
$sanitized_array = array();
foreach( $ids as $id ) {
$sanitized_array[] = intval( $id );
}
// Now that we have all integers in our array, we can safely implode the
// array to be used in a SQL statement.
$ids_string = implode( ', ', $sanitized_array );
$sql = "SELECT * FROM {$table} WHERE {$object_id_column} IN ( {$ids_string} ) AND meta_key = %s";
In both examples, we iterate over the $ids
array and apply the intval()
function to each value.
4 responses to “Sanitize array of integers in PHP”
Thanks for sharing. I haven’t used array_map much, but I’m guessing it would be more efficient then the foreach loop because it’s a native function. Is that the case?
That is a good question sir. I didn’t know, so I checked the developer handbook, StackOverflow. 🙂
Based on this article, it looks like
array_map()
is actually slower thanforeach()
.That being said, I don’t think that
array_map()
is so much slower thanforeach()
that you should always useforeach()
. Ultimately, you’ll probably want to go with whatever you believe is more readable.Fwiw it should perform about the same, the most expensive part of this process is most likely intval() call, not array_map or foreach. Casting with (int) could be faster, I’m curious Eric, can you run a comparison for us casting with (int) instead?
It’s not very scientific, but here are the results from my testing.
Which is interesting, because it contradicts articles I read that suggested casting was faster. Here is the script I used to test if you’re interested. It’s likely I made a mistake. ¯_(ツ)_/¯