Check If Array Position Exists

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
cfytable
Forum Commoner
Posts: 29
Joined: Thu May 12, 2005 3:36 pm

Check If Array Position Exists

Post 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]
noahkeller
Forum Newbie
Posts: 11
Joined: Thu Apr 26, 2007 2:07 pm

Post by noahkeller »

one thing I noticed is ++$i is supposed to be $i++
cfytable
Forum Commoner
Posts: 29
Joined: Thu May 12, 2005 3:36 pm

Post 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.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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
}
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post 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
Post Reply