associative to numeric array

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
User avatar
MichaelSK
Forum Newbie
Posts: 4
Joined: Wed Feb 24, 2010 4:15 pm
Location: Seattle

associative to numeric array

Post 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
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: associative to numeric array

Post by requinix »

How about array_values?
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: associative to numeric array

Post 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;
}
Last edited by AbraCadaver on Wed Feb 24, 2010 4:53 pm, edited 1 time in total.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
User avatar
MichaelSK
Forum Newbie
Posts: 4
Joined: Wed Feb 24, 2010 4:15 pm
Location: Seattle

RESOLVED : associative to numeric array

Post by MichaelSK »

Resolved....

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

brain fart.

Thanks guys.

cheers,
Mike
Post Reply