Reputation: 429
how can I achieve this correctly:
$array[]['title'] = $secondarray["title"];
$array[]['content'] = $secondarray["content"];
foreach($array as $arr) {
$output.="<div>".$arr['title']."</div><br/>";
}
unset($arr);
Now for example the $array[]['title']
contains 10 entries and $array[]['content']
also 10.
But the foreach loop will give 20 div as result since the $array
contains 10+10 elements. How can I tell the foreach to take only the amount of elements in $array[]['title']
(since $array[]['content']
is the content that belongs to each title)? So that means go only 10 times through the loop.
PS: Please no answer that I should use "for".
Thanks for your help, phpheini
Upvotes: 0
Views: 1338
Reputation: 265181
i suggest putting title and content into a single array, then you can use foreach without counting and title with its content is 'grouped':
$array[] = array ( 'title' => $secondarray['title'], 'content' => $secondarray['content'] );
foreach($array as $arr) {
echo '<h1>',htmlspecialchars($arr['title']),'</h1>';
echo '<p>',htmlspecialchars($arr['content']),'</p>';
}
Upvotes: 1
Reputation: 145482
Another method would be to only feed it a partial array:
foreach (array_slice($array, 0, 10) as $row)
{
...
Upvotes: 4
Reputation: 4539
maybe
$array[] = array(
'title' => $secondarray["title"],
'content' => $secondarray["content"],
);
after it will be no need to limit loop times
Upvotes: 1
Reputation: 2611
Use something like this, but you should really use LIMIT if data comes from database.
$i = 0;
foreach($array as $arr) {
$i++;
$output.="<div>".$arr['title']."</div><br/>";
if ($i == 10) break;
}
Upvotes: 1