[SOLVED]in_array function on array values of varying length

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
hairyjim
Forum Contributor
Posts: 219
Joined: Wed Nov 13, 2002 9:04 am
Location: Warwickshire, UK

[SOLVED]in_array function on array values of varying length

Post 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
Last edited by hairyjim on Wed Jun 29, 2005 9:40 am, edited 1 time in total.
User avatar
delorian
Forum Contributor
Posts: 223
Joined: Sun May 04, 2003 5:20 pm
Location: Olsztyn, Poland

Post 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.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post 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;
}
hairyjim
Forum Contributor
Posts: 219
Joined: Wed Nov 13, 2002 9:04 am
Location: Warwickshire, UK

Post by hairyjim »

Excellent - I didn't realise such things could be done with an array.

This works a treat!

Jim
Post Reply