Page 1 of 1

array_keys

Posted: Mon Sep 10, 2007 11:07 am
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?

Posted: Mon Sep 10, 2007 12:55 pm
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
)

Problem solved

Posted: Tue Sep 11, 2007 4:36 am
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.

Posted: Tue Sep 11, 2007 5:41 am
by CoderGoblin
mysql_fetch_assoc may also be of interest.