Page 1 of 1
Getting the first index of an associative array
Posted: Wed Jul 25, 2007 1:56 pm
by superdezign
Code: Select all
if(!empty($_GET))
{
foreach($_GET as $get) break;
if($get == $foo)
{
....
}
}
I am making links like
http://www.domain.tld/page.php?foo instead of the traditional ?foo=bar query string, but I don't want to give any particular action priority over another in case someone were to (strangely) enter more than one into the query string. I'd want it to, expectedly, take the first one and display according to it. The foreach is the only way that I know of to get an associative array in order.
Is there another way to do this (a function perhaps?), or should I just be content with this method?
Posted: Wed Jul 25, 2007 2:24 pm
by volka
maybe
Code: Select all
<?php
$a = array('a'=>null, 'b'=>null);
reset($a);
list($k,$v) = each($a);
echo $k;
?
Posted: Wed Jul 25, 2007 2:24 pm
by miro_igov
Code: Select all
if(is_array($_GET)) {
reset($_GET);
echo current($_GET);
}
Posted: Wed Jul 25, 2007 2:32 pm
by superdezign
It's true... There are array functions for everything.
I've just realized that if for some reason (one that's actually more possible) there is a get variable before one of the one's I am after, then I'd completely miss it. So, now I'm doing it this way:
Code: Select all
foreach($_GET as $get) if(in_array($get, $validChoices)) break;
After making that change, it seems as though I may as well just stick with the foreach.
Posted: Wed Jul 25, 2007 2:34 pm
by miro_igov
I wonder how your foreach will work if in the GET there is name=value pair. Maybe the $get will be an array and in_array will throw error.
Posted: Wed Jul 25, 2007 2:36 pm
by Benjamin
Code: Select all
$result = array_unshift(array_flip(array('key1' => 'foo', 'key2' => 'bar')));
Posted: Wed Jul 25, 2007 2:37 pm
by superdezign
astions wrote:Code: Select all
$result = array_unshift(array_flip(array('key1' => 'foo', 'key2' => 'bar')));
I was trying to remember why I hadn't actually wrote the code yet. That was the problem. :-p
Thanks. ^_^
Posted: Wed Jul 25, 2007 2:42 pm
by miro_igov
There are too much array functions and if you ask 100 coders to do specific array manipulation they all will provide different solutions

Posted: Wed Jul 25, 2007 2:45 pm
by superdezign
miro_igov wrote:There are too much array functions and if you ask 100 coders to do specific array manipulation they all will provide different solutions

True. array_flip was all I was after. I couldn't remember the function name. ;_;
I'm not going to need array_unshift, though. in_array can take any value.
Posted: Wed Jul 25, 2007 4:57 pm
by stereofrog
Code: Select all
$ary = array('foo'=>1, 'bar'=>2);
echo key($ary); // foo
hth
