Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
print associative array using for construct ,
and without array_keys function ?

What I have tried:

PHP
$arr = array(
 
"Italy"=>"Rome", "Luxembourg"=>"Luxembourg", "Belgium"=> "Brussels", "Denmark"=>"Copenhagen", "Finland"=>"Helsinki", "France" => "Paris", "Slovakia"=>"Bratislava", "Slovenia"=>"Ljubljana", "Germany" => "Berlin", "Greece" => "Athens", "Ireland"=>"Dublin", "Netherlands"=>"Amsterdam", "Portugal"=>"Lisbon", "Spain"=>"Madrid", "Sweden"=>"Stockholm", "United Kingdom"=>"London", "Cyprus"=>"Nicosia", "Lithuania"=>"Vilnius", "Czech Republic"=>"Prague", "Estonia"=>"Tallin", "Hungary"=>"Budapest", "Latvia"=>"Riga", "Malta"=>"Valetta", "Austria" => "Vienna", "Poland"=>"Warsaw"

);
    

$c = count($arr);
    

    for ($i = 1; $i < $c; $i++) {
        echo $i . "  :  " . $arr[$i];
    }
Posted
Updated 9-Oct-23 22:58pm
v2

1 solution

Should be as simple as:

PHP
<?php

foreach ($arr as $key => $value) {
  echo $key.' has the capital '.$value;
}
 
Share this answer
 
Comments
user6question 10-Oct-23 8:15am    
it works ,

but, for cannot do it ?
Chris Copeland 10-Oct-23 9:16am    
Well yes you could use array_keys() to get the keys of the array and then iterate over them using a for() loop, but you've already said you don't want to do that. The way I've suggested is probably the easiest solution, why can you not use foreach() instead?
user6question 11-Oct-23 3:37am    
for large data , to avoid another array which array_keys() gives ,
Chris Copeland 11-Oct-23 8:19am    
I probably wouldn't worry about it too much to be honest, the keys of an array are likely to be significantly smaller than than the actual values. And to be honest using foreach() is probably more cost-effective anyway, so I'd focus on using that instead.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900