array_keys

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
amharic06
Forum Newbie
Posts: 2
Joined: Mon Sep 10, 2007 10:55 am

array_keys

Post by amharic06 »

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?
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post by anjanesh »

Code: Select all

$a = array('key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3');
print_r(array_keys($a));
gives

Code: Select all

Array
(
    [0] => key1
    [1] => key2
    [2] => key3
)
amharic06
Forum Newbie
Posts: 2
Joined: Mon Sep 10, 2007 10:55 am

Problem solved

Post by amharic06 »

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.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

mysql_fetch_assoc may also be of interest.
Post Reply