Page 1 of 1

associative to numeric array

Posted: Wed Feb 24, 2010 4:32 pm
by MichaelSK
Hi,

I need something hopefully simple. I have an associative array and I need to change it to a numerical array. Basically change the key association from string to numeric. Or, be able to index an associative by a numeric index.

start with...

$arr = array ("key1" => "value1", "key2" => "value2" .... etc);


what I need to have is a way to get at the second element by number. For instance, shuffle converts the key association to numeric, which is OK since its suppose to be random. then I can access it something like : "$some_value = $arr[rand(0, count($arr) -1];" (This may be a bad example because here I could do a shuffle($arr); $val = $arr[0]. BUT. id lose the string keys. no?)

I don't want to use an iterator. That's what I am doing now and it sucks.

cheers,
Mike

Re: associative to numeric array

Posted: Wed Feb 24, 2010 4:42 pm
by requinix
How about array_values?

Re: associative to numeric array

Posted: Wed Feb 24, 2010 4:45 pm
by AbraCadaver
So you want to access an array item by a string key and a numeric key? If so, here are two off the top of my head. The first one stores them as seperate elements so a change to one won't change the other. The second uses references, so if you change one, it will change the other. Not sure if this is what you want:

Code: Select all

$arr = array ("key1" => "value1", "key2" => "value2");
$new = array_merge($arr, array_values($arr));
 
// or
 
foreach($arr as $value) {
    $arr[] =& $value;
}

RESOLVED : associative to numeric array

Posted: Wed Feb 24, 2010 4:52 pm
by MichaelSK
Resolved....

$arr2 = array_values($tables); // perfect.

brain fart.

Thanks guys.

cheers,
Mike