Reputation: 1786
I have this array:
Array
(
[boks_1] => Array
(
[tittel] => Test
[innhold] => This is a test text
[publish] => 2
)
[boks_2] => Array
(
[tittel] => Test 3
[innhold] => This is a text test
[publish] => 1
)
[boks_3] => Array
(
[tittel] => Kontakt oss
[innhold] => This is a test text
[publish] => 1
)
)
How can I use PHP count()
to count how many times [publish] => 1
appears in my array? I am going to use the value to control the width of divs
in a flexbox container.
Upvotes: 3
Views: 105
Reputation: 78994
For fun:
$count = array_count_values(array_column($array, 'publish'))[1];
publish
keys1
s using index [1]
O.K. more fun:
$count = count(array_keys(array_column($array, 'publish'), 1));
publish
keys1
NOTE: You might want to pass true
as the third argument to array_keys()
to be more accurate and use '1'
instead of 1
if the 1
s are strings and not integers.
Upvotes: 6
Reputation: 2683
$newArray = array_filter($booksArray, function($bookDet) { if($bookDet["publish"]==1) { return $bookDet; } });
$getCount = count($newArray);
use array_filter
to filter out only required array details, and get a count of it.
this could be the simplest, and performance oriented as well, as it won't loop.
Upvotes: 3
Reputation: 1757
this should solve your problem :
$array = array(); //This is your data sample
$counter = 0; //This is your counter
foreach ($array as $key => $elem) {
if (array_key_exists('publish', $elem) && $elem['publish'] === 1) {
$counter += $elem['publish'];
}
}
hope this'll help,
Upvotes: 1