john john john john - 3 months ago 8
PHP Question

how to count array which has the same attribute

I have an array like below. What I want is to echo a word according to number of

$my[]['title']
items. in this case the word must be repeated 4 times.
the sudo code is sth like this:

<?php
$my[0]['title']='first title';
$my[0]['description']='description';
$my[0]['date']='date';
$my[1]['title']='second title';
$my[1]['description']='description';
$my[1]['date']='date';
$my[2]['title']='third title';
$my[3]['title']='forth title';

for($i=0;$i<count($my[]['title'];$i++)
echo 'this is test';
?>

Answer

Your test data would work fine with a foreach loop, but assuming that your array can contains rows that don't have a title key, you can use array_column:

$count = count(array_column($my, 'title'));

for($i=0; $i<$count; $i++) {
    echo 'this is test';
}