Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

sanitize int returns string

I try to sanitize an integer

$myInt = $this->filter->sanitize(34, "int");


The output is string '34' (length=2). Is this a bug or am I missing something?

As I do this very dynamically in my code I can't add (int)

Best, Thorsten

Why can't you cast it to an int?

$myInt = (int)$this->filter->sanitize(34,"int");

I've an array which handles the sanitization:

$allowedFields = ['firstName' => 'string', 'lastName' => 'string', 'age' => 'int'];

I realy don't get why an integer santization returns a string.


I don't use sanitization like that, so I had to re-read the docs. The sanitization doesn't ensure the field is of the specified type (ie: it doesn't ensure 34 is an integer), it just removes any characters that aren't allowed in the specified type. So, "34abc" sanitized would return "34". Numbers don't have "characters" per se, so the variable needs to be converted to a string so (presumably) the appropriate regex can be run on it. I believe the built-in (to PHP) filters do the same thing.

You can write your own filters: You could write your own that casts to the integer type after sanitization.


Just added:

    'filter', function () {
        $filter = new \Phalcon\Filter();

        // Change int filter to return int
            'int', function ($value) {
                return (int) filter_var($value, FILTER_VALIDATE_INT);

        return $filter;

Good to see. Please accept an answer so this thread gets flagged as "solved"