Page 1 of 1

[SOLVED]in_array function on array values of varying length

Posted: Wed Jun 29, 2005 7:26 am
by hairyjim
Hi,

Using arrays is still fairly new stuff for me.

I have an validation function that utilises an array of values to check against:

Code: Select all

$valid_dongle = true;

$dongle_array = array('410',
'411',
'413',
'414',
'415',
'416',
'417',
'418',
'420',
'444',
'1000',
'1001',
'1002',
'1096',
'1097',);

$dongle_number = substr($dongle, 0, 4);	
	
if (!in_array($dongle_number, $dongle_array))
	{
		$valid_dongle = false;
	}
		
return $valid_dongle;
A user enters a number in an input box and I am trying to identify if any of the above numbers match the beginning of the inputted string.

The problem I have is if I enter 4205469, obviously my code takes the first 4 digits and checks them against the array. The check would come back false even though the first three digits (420) are valid.

Now my first thought was to take the first three but then I could enter 10973265, this would not return true because 109 does not exist in the array but 1097 is a legitimate combination.

I hope this makes sense, could someone offer help please.

Regards
Jim

Posted: Wed Jun 29, 2005 8:58 am
by delorian
I believe that you could create your own function for checking if the number is valid and then use it in array_walk as a callback. In that callback function if you want to check if the begining of the number is valid you could use preg_match function with regular expressions created dynamically.

Posted: Wed Jun 29, 2005 9:27 am
by timvw
Untested, but logic should be obvious...

Code: Select all

function is_valid_dongle($dongle_number, $dongle_array)
{
  foreach($dongle_array as $dongle)
  {
    if ($dongle == substr($dongle_number, 0, strlen($dongle))
    {
      return true;
    } 
  }
  return false;
}

Posted: Wed Jun 29, 2005 9:40 am
by hairyjim
Excellent - I didn't realise such things could be done with an array.

This works a treat!

Jim