It is possible yes. Just check if it is an integer or value number and if it is not, display an error message.
Using preg_match:
<?php
/* Verifica se a variável contém somente números */
if (preg_match("/^\d+$/", $id)) {
/* Faz a busca */
}
Using is_numeric:
<?php
/* Verifica se a variável contém um valor número, independente da variável ser do tipo "int" ou "string" */
if (is_numeric($id)) {
/* Faz a busca */
}
Using is_int or is_integer:
<?php
/* Verifica se a variável é do tipo "inteiro" */
if (is_int($id)) {
/* Faz a busca */
}
You can also convert to whole.
<?php
$id = "4165";
var_dump( (int)"4165" ); // 4165
var_dump( (int)4165.7 ); // 4165
var_dump( (int)false ); // 0
var_dump( (int)true ); // 1
var_dump( (int)"valdeir" ); // 0
echo PHP_EOL;
echo "----------";
echo PHP_EOL;
var_dump( intval("4165") ); // 4165
var_dump( intval(4165.7) ); // 4165
var_dump( intval(false) ); // 0
var_dump( intval(true) ); // 1
var_dump( intval("valdeir") ); // 0
If you have using multiples ID’s, you can use the function array_map
. Ex:
<?php
$ids = ["4165", 4165.7, false, true, "valdeir"];
$newIds = array_map(function($value) {
return (int)$value;
}, $ids);
var_dump($newIds);
You can also filter only numbers values.
<?php
$ids = "4165,4165.7,false,true,valdeir,12";
$ids = explode(",", $ids);
$newIds = array_filter($ids, function($value) {
/* Retorna apenas os números inteiros */
return is_numeric($value);
});
var_dump( implode(",", $newIds) );
// Output: 4165,4165,12
Each ID and separated by comma will still work?
– Gabriel
@Gabriel using the function
array_map
works yes. I added a new function to filter only number values. Just useexplode
to turn intoarray
and then theimplode
to join only the new values.– Valdeir Psr
use the $ids = explode(",", $ids); and ( implode(",", $newIds)) will remove the last comma, "if any", because the id captures with"," in front, sometimes it gets something like ids="1,2,3,4,"
– Gabriel
@Gabriel if there is a comma at the end of the string, the explode will return an empty value and the array_filter will delete that value. Thus "1,2,3,4," will become "1,2,3,4"
– Valdeir Psr
Demonstration: https://ideone.com/ELeIc
– Valdeir Psr