user5154930
user5154930

Reputation:

Check if string is a comma-separated list of digits

In my table1 i have varchar field where i store an id-list of other table2 (id - INT UNSIGNED AUTOINCREMENT), separated by comma.

For example: 1,3,5,12,90

Also ids should not be repeated.

I need to check if a string (coming from outside) matches this rule. For example i need to check $_POST['id_list']

Data consistency is not important for now (for example insert this value without checking if this ids really exist in table2)

Any advice will be helpful.

Upvotes: 2

Views: 2635

Answers (3)

RiWe
RiWe

Reputation: 377

For the sake of completeness I would like to mention the following solution:

<?php

$check = explode(',', $string);
if ($diff = array_diff_key($check, array_filter($check, 'ctype_digit'))) {
    // at least one is not a digit
    foreach ($diff as $failIndex => $failValue) {
        // handle
    }
}

For less than 1000 digits in the string this is a little faster than preg_match and as little extra you get the positions and the values that are not a digit.

Upvotes: 1

M0rtiis
M0rtiis

Reputation: 3774

The easiest way to do such check is to use regular expression (preg_match). Lets try to find a pattern matching our rule.

Just comma-separated digits:

^[0-9]+(,[0-9]*)*$ 

^ - means start of string. $ - means end of string. [0-9]+ - means that our string MUST starts with a digits. (,[0-9]+)* - means that our string CAN continue itself with ",$someDigits" manner, from 0 to as many you wish times.

But if our digits are "INT UNSIGNED AUTOINCREMENT" we should modify our pattern this way:

^[1-9][0-9]*(,[1-9][0-9]+)*$

to exclude cases like: 0,01,02,009,000,012

As for unique values, i think more clear will be to use splitting (explode) string by comma to array, pass it through array_unique and compare.

So the result check-function will be:

function isComaSeparatedIds($string, $allowEmpty = false) {
    if ($allowEmpty AND $string === '') {
        return true;
    }
    if (!preg_match('#^[1-9][0-9]*(,[1-9][0-9]*)*$#', $string)) {
        return false;
    }
    $idsArray = explode(',', $string);
    return count($idsArray) == count(array_unique($idsArray));
}

Also added $allowEmpty argument if u would like to allow empty strings.

Upvotes: 10

Varun
Varun

Reputation: 1946

This is a bit of a cheeky solution,but it sure does the work.

<?php

$a="1,3,5,12,90";
$b=explode(",",$a);
$str='';

for($c=0;$c<count($b);$c++)
{
    if (preg_match('/^[0-9]+$/', $b[$c])) 
    {
        $str=$str."Y";
    }
}

if(count(array_unique($b))==count($b)  && (count($b)==strlen($str)))
{
   echo $str;
    //FURTHER CODE HERE WHEN ALL ELEMENTS UNIQUE AND VALID NUMBERS
}
else
{
    //FURTHER CODE HERE WHEN NOT UNIQUE OR NOT A VALID NUMBERS
}
?>

Upvotes: 0

Related Questions