Que :- Create an associative array with a few countries as indexes(keys) and their respective capitals as values. Create a function which takes the country name as argument and returns it's capital city.
Here's the code that I wrote :-
<html>
<head>
<title> Function</title>
</head>
<body>
<?php
function capitalof ($country) //creating the function 'capitalof'
{
$capital=array( );
$ans;
foreach ($capital as $key => $value)
{
if ($key==$country)
{
$ans=$value;
}
}
return $ans; //returns the value of the index
}
$capitals["FRANCE"]="Paris";
$capitals["PAKISTAN"]="Islamabad";
$capitals["ITALY"]="Rome";
$capitals["ENGLAND"]="London"; //defining associative array
$capitals["GERMANY"]="Berlin";
$capitals["USA"]="Washington";
$capitals["EGYPT"]="Cairo";
$capitals["SWITZERLAND"]="Bern";
foreach ($capitals as $key => $value)
{
echo ("<h1>Capital of $key is $value</h1>"); //printing each values with their respective indexes
}
$cap=capitalof("FRANCE"); //using 'capitalof' to get the capital of India
echo ("<h1>Using function, France's capital is $cap</h1>");
?>
</body>
</html>
I am getting the output while not using the function 'capitalof'. But I can't seem to understand why no output whilst the function is being used.
But when I put the array inside the function, I am getting the result :-
<html>
<head>
<title>Function</title>
</head>
<body>
<?php
function capitalof($country) //creating the function 'capitalof'
{
$capitals["FRANCE"]="Paris";
$capitals["PAKISTAN"]="Islamabad";
$capitals["ITALY"]="Rome";
$capitals["ENGLAND"]="London"; //defining associative array
$capitals["GERMANY"]="Berlin";
$capitals["USA"]="Washington";
$capitals["EGYPT"]="Cairo";
$capitals["SWITZERLAND"]="Bern";
$ans;
foreach ($capitals as $key => $value)
{
if ($key == $country)
{
$ans = $value;
}
}
return $ans; //returns the value of the index
}
$capitals["FRANCE"]="Paris";
$capitals["PAKISTAN"]="Islamabad";
$capitals["ITALY"]="Rome";
$capitals["ENGLAND"]="London"; //defining associative array
$capitals["GERMANY"]="Berlin";
$capitals["USA"]="Washington";
$capitals["EGYPT"]="Cairo";
$capitals["SWITZERLAND"]="Bern";
foreach ($capitals as $key => $value)
{
echo ("<h1>Capital of $key is $value</h1>"); //printing each values with their respective indexes
}
$cap = capitalof("FRANCE"); //using 'capitalof' to get the capital of India
echo ("<h1>Using function, France's capital is $cap</h1>");
?>
</body>
</html>
If I take out the index France from the function, it doesn't work while executing. No errors mentioned. I can't seem to figure out why. Can someone help me?