Destramic Posted May 27, 2011 Share Posted May 27, 2011 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 <?php $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 news Quote Link to comment https://forums.phpfreaks.com/topic/237650-array-keys-and-values-help/ Share on other sites More sharing options...
mikesta707 Posted May 27, 2011 Share Posted May 27, 2011 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 Quote Link to comment https://forums.phpfreaks.com/topic/237650-array-keys-and-values-help/#findComment-1221207 Share on other sites More sharing options...
The Little Guy Posted May 27, 2011 Share Posted May 27, 2011 Assuming you will never have anything starting with a digit: <?php $columns = array('news_id' => 'id', 'news'); foreach ($columns as $column => $column_alias) { echo ((!preg_match("/^\d/", $column))?$column:"") . ' ' . $column_alias; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/237650-array-keys-and-values-help/#findComment-1221208 Share on other sites More sharing options...
Destramic Posted May 30, 2011 Author Share Posted May 30, 2011 thanks guys Quote Link to comment https://forums.phpfreaks.com/topic/237650-array-keys-and-values-help/#findComment-1222576 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.