View Full Version : Finding vars

01-21-2010, 10:34 PM
Ok here's the deal ha ha. I have this script that receives GET parameters in the form of:

item_number1 = Download
item_number2 = Tangible

But I have no idea of knowing at run time how many item_numerX there are. I have to go through each one and do something with it. So my question is, how do I find out how many of those item_numbers there are in the GET sequence to know how many times I have to go through it? Or do I just go until it breaks?

Thanks for any help in this matter.

01-21-2010, 10:43 PM
Here's something I cam up with a while back on another forum:

Also see: http://www.php.net/preg_grep for further details. All this does is run preg_grep() on the array keys as opposed to the values.

function preg_grep_keys( $pattern, $input, $flags = 0 )
$keys = preg_grep( $pattern, array_keys( $input ), $flags );
$vals = array();
foreach ( $keys as $key )
$vals[$key] = $input[$key];
return $vals;

$matches = preg_grep_keys( '/^item_number\d+$/', $_GET );

count( $matches ); // # of matching keys from array

$matches is an associative array of the matching keys and their values, so you can just iterate that instead.

01-21-2010, 11:27 PM
Perfect just what I was looking for, thanks. I didn't know your could preg match with variable names.

01-21-2010, 11:28 PM
Well, not natively... hence the custom function. :)