Reputation: 13
I've got a MySQL table like this;
╔════╦═══════════════════════╗
║ id ║ comma_separated_stuff ║
╠════╬═══════════════════════╣
║ 1 ║ 1, 2, 3, 4, 5 ║
║ 2 ║ 1, 2, 5 ║
║ 3 ║ 3, 7 ║
║ 4 ║ 4, 8 ║
╚════╩═══════════════════════╝
I managed to get each rows into arrays as array[0], array[1], array[2] and array[3]. The question is how to count "how many of the comma-separated-arrays include -for example- '5'?"
Upvotes: 0
Views: 588
Reputation: 4302
the following two examples if you would like to count how many keys among the array itself by :
<?php
$a[0] = '1, 2, 3, 4, 5';
$a[1] = '1, 2, 5';
$a[2] = '3, 7 ';
$a[3] = '4, 8';
$resulta = count($a);
print $resulta;// Output 4
?>
Another one:
<?php
$b = array ('1, 2, 3, 4, 5','1, 2, 5' ,'3, 7','4, 8');
$resultb = count($b);
print $resultb;// Output 4
?>
the following one if you would like to count the number of comma from string :
$text = 'This , is, , a , test a,a,';
echo substr_count($text, ','); // Output 6 , will give the number of comma in each one
Upvotes: 0
Reputation: 23749
<?php
//how many of the comma-separated-arrays include for example '5'
$array = array(
'1, 2, 3, 4, 5',
'1, 2, 5',
'3, 7',
'4, 8',
);
$n = 5;
$sum = 0;
//Split the strings to arrays of numbers
foreach($array as $value)
{
$data = explode(', ', $value);
if (in_array($n, $data))
{
++$sum;
}
}
//prints 2
print $sum;
Upvotes: 1