I am trying to access the keys of an array, using the array_keys function.
The problem is that the array returned by the array_keys function includes as elements a numeric index for each key, as well as the keys themselves, so that the elements I am interested in are every (2n+1)th element.
I seem to recall there is some parameter I need to set to change this behaviour but trawling through documentation and forums leaves me none the wiser.
I want array_keys to give me
[0] => key1
[1] => key2
[2] => .... etc ....
but at the moment I am getting
[0] => 0
[1] => key1
[2] => 1
[3] => key2
[4] => 2
[5] => .... etc ....
can anyone help?
array_keys
Moderator: General Moderators
Code: Select all
$a = array('key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3');
print_r(array_keys($a));Code: Select all
Array
(
[0] => key1
[1] => key2
[2] => key3
)Problem solved
Thanks for the reply. It didn't address my issue, which is OK because I find I hadn't really expressed myself clearly in the original post. My problem arose when trying to get field names for a MySQL table using the following code...
$result = mysql_query("SELECT * FROM tblTable;");
$row = mysql_fetch_array($result);
$keys = array_keys($row);
Of course I have now discovered my problem was not with the array_keys() function but with the mysql_fetch_array() function. I omitted to include the optional argument specifying whether I wanted associative, numeric, or both keys, and the default is both. I wanted only the associative ones. I should have used
$row = mysql_fetch_array($result, MYSQL_ASSOC);
to get the behaviour I wanted.
$result = mysql_query("SELECT * FROM tblTable;");
$row = mysql_fetch_array($result);
$keys = array_keys($row);
Of course I have now discovered my problem was not with the array_keys() function but with the mysql_fetch_array() function. I omitted to include the optional argument specifying whether I wanted associative, numeric, or both keys, and the default is both. I wanted only the associative ones. I should have used
$row = mysql_fetch_array($result, MYSQL_ASSOC);
to get the behaviour I wanted.
- CoderGoblin
- DevNet Resident
- Posts: 1425
- Joined: Tue Mar 16, 2004 10:03 am
- Location: Aachen, Germany
mysql_fetch_assoc may also be of interest.