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';
?>
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';
}
This is what foreach
is for. It iterates over your entire array
foreach($my as $row) echo 'This is my test;
This echos whatever you want once per array entry
$count = 0;
foreach($my as $val){
if(isset($val['title'])){
echo 'this is test';
$count++;
}
}
Outputs "this is test" depending on how many times it see the title
index.
Working code: http://sandbox.onlinephpfunctions.com/code/9c19bfac8fedb02a9840cdfb4f9217ccb110c7bc
You can use array_column
:
$titleCount = count(array_column($my, 'title'));
for($i=0; $i<$titleCount; $i++)
echo 'this is test';
?>
http://php.net/manual/en/function.array-column.php
As per the linked manual, this is available from php v5.5.
If you are using an older version (you should really update...) then here is the equivilent user defined function (from the manual comments section):
if(!function_exists("array_column"))
{
function array_column($array,$column_name)
{
return array_map(function($element) use($column_name){return $element[$column_name];}, $array);
}
}
If you are using php5.5 and above, use array_column function to catch all the keys you want and then count them.
$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';
$a = array_column($my, 'title');
if (count($a) >= 4) {
# your code
}
If you do use the array_column
method (as many people have rightly recommended), you don't need to use a loop. You can use str_repeat
instead.
echo str_repeat('this is test', count(array_column($my, 'title')));
foreach($my as $key => $val){
if ( isset( $val['title']) ){
echo $key;
}
}