Jump to content

array keys and values help


Recommended Posts

hey guys im trying to result an array key and value if it has one...the code and results are below if anyone can help with this simple problem...thanks alot



$columns = array('news_id' => 'id', 'news');

	foreach ($columns as $column => $column_alias)
		echo $column . ' ' . $column_alias;


the result im getting is:


news_id  id

0 news


but im just after the result of just result the column name and alias (if it has one)

so im looking for the result


news_id  id


Link to comment
Share on other sites

When you don't provide a specific key for a value in an array, PHP automatically uses the next available numeric index. In your example, the next available one would be the first numerical index, which is 0. So for example, if I used the following array in your code

$arr = array("key" => "value", "value2", "value3");


then the result would be

key value
0 value2
1 value3




This is how PHP works, and you won't really be able to achieve the result you are looking for. Why exactly are you trying to have an empty string as an array key? This kind of defeats the purpose of an associative array


EDIT: Oh I realize what you were getting at, sorry I missread your post. Are you just trying to check if the key=>value pair has a non numeric index? In that case you can use what TLG posted. However, for such a simple pattern, regex seems like overkill. The is_numeric() function should suffice. For example

$arr = array(... some stuff in here ...)

foreach ($arr as  $key => $value){
    if (is_numeric($key) {
        //there was no key name for this entry
    } else {
        //this entry has a key name
}//end foreach

Link to comment
Share on other sites


This topic is now archived and is closed to further replies.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.