How to echo a letter multiple times, changing more then one variable in it for each new print?

Viewed 128

Hello all! This is my first question in stackoverflow so I hope I follow the rules good enough. :)

For my PHP class I have an exercise that makes it difficult for me: Text with about 4 variables in it, all are stored in arrays (one array for each variable, 3 values for each variable). Position [0] of each array goes in the first echo text, position [1] of each array goes in the second text and so on.
How to echo the text 3 times using all values stored in the array? In the code I must use the main text only 1 time.

$u_name = array('student' => 'Joe','lecturer' => 'Kate', 'assistant' => 'Martin');
$course_name = array('PHP', 'CSS', 'HTML');
$role = array('student', 'lecturer', 'assistant');

echo "Hi," . $u_name['student'] . "! You've been approved to take part in course " . $course_name[0] . " as a " . $role[0] . ". The course " .  $course_name[0] . " will last for two days.";
echo "<br>";
echo "Hi," . $u_name['lecturer'] . "! You've been approved to take part in course " . $course_name[1] . " as a " . $role[1] . ". The course " .  $course_name[1] . " will last for two days.";
echo "<br>";    
echo "Hi," . $u_name['assistant'] . "! You've been approved to take part in course " . $course_name[2] . " as a " . $role[2] . ". The course " .  $course_name[2] . " will last for two days.";

This is what I did by myself, but as you see in the code I have 3 times the main text.
Thank you in advance.
1 Answers

Normally you go trough arrays with some type of a loop.

To name a few types of loops:

  1. for
  2. while
  3. foreach

In this case the perfect fit is a foreach loop.

It simply goes through each element of the array, but because you have a associative array and two indexed array you also need a counter.

$counter = 0;
foreach($u_name as $key=>$value){
    echo "Hi, " . $value . "! You've been approved to take part in course " . $course_name[$counter] . " as a " . $role[$counter] . ". The course " .  $course_name[$counter] . " will last for two days.";
    echo "<br>";
    $counter++;
}

If still are any questions left, don't mind to ask.

Related