Lior Elrom
Lior Elrom

Reputation: 20862

Finding how many times a number exists inside an array

I have an array that looks like this:

$numbers = array("332467323232", "750327430375", "332503248632", ...);

I would like to get the number of times that the number 32 (or any other number) is showing up in every string inside my array.

Example:

$times = array(4, 1, 3, ...);

Upvotes: 0

Views: 78

Answers (2)

Harry Mustoe-Playfair
Harry Mustoe-Playfair

Reputation: 1419

You might not need regex, for example:

$numbers = array(
    32323232, # 4
    12233232, # 2
    12314232, # 1
    12349085, # 0
);

$result = array();

foreach($numbers as $num){
    $result[] = substr_count("$num", '32');
}

print_r($result);

//  Array
// (
//     [0] => 4
//     [1] => 2
//     [2] => 1
//     [3] => 0
// )

This should do what you're looking for. substr_count on php.net

Upvotes: 1

Jon
Jon

Reputation: 437366

Correct answer:

$times=array_map(function($str) { return substr_count($str, "32"); }, $numbers);

Initial answer (wrong, misread the question, sorry!):

Here's an one-liner which does not use regular expressions:

echo array_sum(array_map(
                  function($str) { return substr_count($str, "32"); },
                  $numbers));

Upvotes: 4

Related Questions