Jim
Jim

Reputation:

PHP - Is there a way to verify all values in an array

Using PHP..

Here is what I have.. I'm gonna explain the whole thing and maybe someone can help me with the logic and maybe point me in the right direction.

I have a mail system I am working on. In the cc part, I am allowing the user to seperate the values by a semicolon, like so: 1;2;3;4...

When these values are passed to my function, I am using explode to get them into an array. What I want to do is some checking first. I want to firstly make certain that the format is correct and that every value is correctly seperated. If not, I should show an error. Once this is done, I want to make certain that every number is actually valid. I can query the database, put the reslts into an array and was thinking to use the in_array() function to verify this but I'm not certain that it will work. Can someone please help me out with the best way to handle this?

Thanks.

EDIT:

What is the best way to detect a bogus value in the CSV list of values?

Upvotes: 0

Views: 213

Answers (4)

fiskah
fiskah

Reputation: 5902

As whichdan suggested, here is an implementation that relies on array_filter():

<?php
function checkValue($value)
{
    $id = trim(id);
    if(!is_numeric($id))
    {
        return false;
    }
    if(strpos(" ", $id) !== false)
    {
        return false;
    } 
    if(!in_array($id, $database_ids))
    {
        return false;
    }
    return true;
}

$values = '1;2;3;4';
$values_extracted = explode(';', $values);

if(count($values) == count(array_filter($values_extracted), 'checkValue'))
{
   // Input was successfully validated
}
?>

Upvotes: 0

whichdan
whichdan

Reputation: 1897

array_filter could be an option.

Upvotes: 0

Tyler Carter
Tyler Carter

Reputation: 61567

In order to verify that each number was correct seperated, you want to check that there is no whitespace in the answer. So something like this should work:

$text = trim($id);
if(strpos(" ", $id) !== false)
{
    //error
}

Next, to check for the values, it is very simple

if(!in_array($id, $database_ids))
{
    // error
}

Finally, if you are only using numeric values, check that the id is numeric

if(!is_numeric($id))
{
    //error
}

To combine, wrap it into an array

foreach($exploded_array as $key => $id)
{
    $id = trim(id);
    if(!is_numeric($id))
    {
        //error
    }
    if(strpos(" ", $id) !== false)
    {
        //error
    } 
    if(!in_array($id, $database_ids))
    {
        // error
    }
}

I hope the code was pretty self explanatory where it got the variables, but if you need me to explain more, feel free to ask.

Upvotes: 3

Kitson
Kitson

Reputation: 1678

You are looking for something like:

foreach ($array as $value) {
   //do checking here
}

Upvotes: 0

Related Questions