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
associative to numeric array
Moderator: General Moderators
Re: associative to numeric array
How about array_values?
- AbraCadaver
- DevNet Master
- Posts: 2572
- Joined: Mon Feb 24, 2003 10:12 am
- Location: The Republic of Texas
- Contact:
Re: associative to numeric array
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.
RESOLVED : associative to numeric array
Resolved....
$arr2 = array_values($tables); // perfect.
brain fart.
Thanks guys.
cheers,
Mike
$arr2 = array_values($tables); // perfect.
brain fart.
Thanks guys.
cheers,
Mike