...

View Full Version : Check type and length of array item



htcilt
02-12-2010, 02:04 PM
I have an array that should contain only single numbers.
each item has been set to an integer.
I want to perform some sort or validation that returns true only if each item is an integer and is only 1 character (integer) long.

e.g.
1 - valid
11 - invalid
a - invalid

I hope someone can help me?

Fou-Lu
02-12-2010, 02:30 PM
The check is a simple if (is_int($val) && $val < 10).
The easiest way to achieve this is to use arrayObject instead of array. Extend it into you're custom class (it can be far more generic than this, but a simple extends should show you the principal):


class IntArray extends ArrayObject
{
public function __construct($in = array(), $flags = 1, $itorClass = 'ArrayIterator')
{
parent::__construct(array(), $flags, $itorClass);
if (count($in) > 0)
{
foreach ($in AS $k => $v)
{
$this[$k] = $v;
}
}
}

public function offsetSet($mKey, $mVal)
{
if (!is_int($mVal) || ($mVal >= 10))
{
throw new RuntimeException('Value must be an integer less than 10!');
}
parent::offsetSet($mKey, $mVal);
}
}

// Usage
$ia = new IntArray();
$ia->append(5);
$ia[] = 3;
$ia[] = 10; // Will toss



I believe the default for the properties is 1, not 0. So I changed that one.

htcilt
02-12-2010, 02:57 PM
Thanks Fou-Lu :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum