(PHP 4, PHP 5, PHP 7)
for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:
for (expr1; expr2; expr3) {
statement
}
The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.
In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.
At the end of each iteration, expr3 is evaluated (executed).
Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression. check
doc
FOREACH LOOP
(PHP 4, PHP 5, PHP 7)
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:
foreach (array_expression as $value) {
statement
}
foreach (array_expression as $key => $value) {
statement
}
The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).
The second form will additionally assign the current element's key to the $key variable on each iteration. DOC
AND Yes your solution is here
<select>
<?php
$citylist = array(
'Adana',
'Adıyaman',
'Afyonkarahisar',
'Ağrı',
'Amasya',
'Ankara'
);
echo populate_option($citylist, "");
?>
</select>
Your function goes here
<?php
function populate_option($citylist, $selected_option = "")
{
foreach ($citylist as $city) {
if ($selected_option !== "" && $city === $selected_option) {
echo "<option value='".$city."' selected>$city</option>";
} else {
echo "<option value='".$city."'>$city</option>";
}
}
}