I have a website and I am using php to print both key and value from an array
$array = array(
"gfo" => "Fondant",
"gdo" => "Domino",
"ges" => "Espir",
"gam" => "Amara",
"gsa" => "Sandwich",
"gme" => "Merme",
"cza" => "Zarza",
"cor" => "Oreo",
"cal" => "Almen",
"cca" => "eche",
"cch" => "Chocolate"
);
but I want ONLY first 6 elements be displayed in a menu like
<li>
<a href="product1.php" style="padding:8px 30px;">Product 1</a>
<ul>
<?php foreach($array as $key=>$val):?>
<li><a href="http://www.site.com.mx/products.php?id=<?=$key?>"><?=$val?></a></li>
<?php endforeach;?>
</ul>
</li>
And then the other 5 elements in other menu
<li>
<a href="product2.php" style="padding:8px 30px;">Product 2</a>
<ul>
<?php foreach($array as $key=>$val):?>
<li><a href="http://www.site.com.mx/products.php?id=<?=$key?>"><?=$val?></a></li>
<?php endforeach;?>
</ul>
</li>
I know I can use
for ($i = 1; $i <= 6; $i++) {
echo $i;
}
and
for ($i = 6; $i <= sizeof($array); $i++) {
echo $i;
}
But how to get the key and value in both for loops?
You can use
eachfor that:Alternatively, you can use
array_slice()but make sure to preserve the keys: