Page 1 of 1

Access associative array using numeric index?

Posted: Fri Jul 09, 2010 12:21 pm
by gadonj
How can I loop through an associative array using a numeric index? I've read around a few places saying you can't and you must use the named key, but I find that odd as you can use mysql_fetch_array to get an array that is both. Here is a simple example that gives me an Undefined Offset warning:

Code: Select all

$array = array('test1' => 'test1_value', 'test2' => 'test2_value', 'test3' => 'test3_value');
for($i=0;$i<count($array);$i++)
{
	echo $array[$i] . "<br />";
}
Is there any way to do what I am trying to do? Please help

Re: Access associative array using numeric index?

Posted: Fri Jul 09, 2010 12:34 pm
by cpetercarter
Why do you need to use a numerical index? "foreach" will do the job for you.

Code: Select all

$array = array('test1' => 'test1_value', 'test2' => 'test2_value', 'test3' => 'test3_value');
foreach ($array as $name=>$value)
{
        echo $value . "<br />";
}

Re: Access associative array using numeric index?

Posted: Fri Jul 09, 2010 12:52 pm
by gadonj
I need to use a numeric index because I only want loop a certain amount of times and I want to use the same numeric index for two associative arrays.

Each element of my array is actually structure somewhat like this:

Code: Select all

main_key =>key1 => value,
			key2 => value,
			key3 =>	key3.1 => value,
						key3.2 => value
			key4 => key4.1 => value
Key3 and key4 could have any number of elements in them, and I want to create as many rows in a table as the higher number of elements in key3 and key4. So I use a foreach on the main_keys but I want to use a for loop within it so that I can loop as many times as the higher number of elements in key3 and key4.

I'm sorry. This is really hard to explain. There are many reasons why I am doing this the way I am doing, and there isn't really an easy way around it. The easiest solution would be if there is a way to use a numerical index in an associative array. If not then I am royally screwed and I have a lot of work rewriting my entire application.

Re: Access associative array using numeric index?

Posted: Fri Jul 09, 2010 1:16 pm
by requinix
gadonj wrote:but I find that odd as you can use mysql_fetch_array to get an array that is both.
That's because it returns an array where both the numerical and associative keys are set. The array has everything twice.

Use array_keys.

Code: Select all

$array = array('test1' =>  'test1_value', 'test2' =>  'test2_value', 'test3' =>  'test3_value');
$keys = array_keys($array); $count = count($keys);
for ($i = 0; $i < $count; $i++) {
    echo $i, " => ", $keys[$i], " => ", $array[$keys[$i]], "\n";
}

Re: Access associative array using numeric index?

Posted: Fri Jul 09, 2010 1:30 pm
by gadonj
Literally like 5 minutes before I came back to check for responses, I discovered the array_keys function. Its a quick and simple solution to my problem! Thanks a bunch guys