Page 1 of 1

Check If Array Position Exists

Posted: Thu Apr 26, 2007 2:59 pm
by cfytable
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


From a web form, I have the following array $_POST['locationKey']. The array positions range from 1 to 90,000 (and are out of order), but not every value in between is represented. For instance:

Code: Select all

$_POST['locationKey'][1] = somevalue
$_POST['locationKey'][3] = somevalue
$_POST['locationKey'][90000] = somevalue
etc
$_POST['locationKey'][14] = somevalue
Given above, how can I find out the maximum position. In other words, the highest [xx]?

I would then like to loop through the array, inserting data wherever the array position exists. Once I get the above value, would the following work correctly using array_key_exists?

Code: Select all

$maximumvalue = max($_POST['locationKey']);

for ($i = 0; $i <= MAXIMUMVALUE; ++$i) {
	if (array_key_exists($i, $_POST['locationKey'])) {
		//INSERT
	} 		
}

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Thu Apr 26, 2007 3:04 pm
by noahkeller
one thing I noticed is ++$i is supposed to be $i++

Posted: Thu Apr 26, 2007 3:05 pm
by cfytable
Please note that I updated the text of my question-- the sample code wasn't consistent with my data. Any help would be appreciated.

Posted: Thu Apr 26, 2007 3:12 pm
by Chris Corbyn
Shouldn't you just be using foreach() rather than for() ? foreach() won't care if the order is out.

EDIT | As in

Code: Select all

foreach ($_POST['locationKey'] as $key => $value)
{
  //do something with $value
}

Posted: Thu Apr 26, 2007 3:30 pm
by aaronhall
noahkeller wrote:one thing I noticed is ++$i is supposed to be $i++
No problems there.. http://www.php.net/manual/en/language.o ... rement.php