Reputation: 1
My goal is to write a php script that prints elements from 4 ("Adam =>16,) to 8 ("Kunegunda" => 42,) in an associative array. My code prints all elements. What i have to change?
$ages = array("Marek" => 22, "Jeacek" => 32, "Michał" => 28, "Adam" => 16, "Adrian" => 25, "Bolesław" => 9, "Jeremi" => 28, "Kunegunda" => 42, "Anna" => 40, "Elżbieta" => 96);
foreach($ages as $x => $x_value) {
echo "Name = " . $x . ", Age = " . $x_value;
echo "<br>";
}
?>
Upvotes: 0
Views: 63
Reputation: 206
get a slice from your array and loop throw it
foreach(array_slice($ages, 4, 4) as $x => $x_value) {
echo "Name = " . $x . ", Age = " . $x_value;
echo "<br>";
}
array_slice will return a new array from your old array (from 4th item with 4steps forward so from 4 to 8) then the foreach wil loop the slice only (from 4 to 8)
Upvotes: 2