Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Sep 2007
    Posts
    238
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Check type and length of array item

    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?

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    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):
    PHP Code:
    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 
    Edit:
    I believe the default for the properties is 1, not 0. So I changed that one.
    Last edited by Fou-Lu; 02-12-2010 at 01:34 PM.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #3
    Regular Coder
    Join Date
    Sep 2007
    Posts
    238
    Thanks
    9
    Thanked 0 Times in 0 Posts
    Thanks Fou-Lu


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •