user4165262
user4165262

Reputation:

find occurence of specific letter in values of an array

I want to find the occurrence of a specific letter in array and also want to count the number of values in which it is present. for example:

<?php 
$aa= array (
  'sayhello',
  'hellostackoverflow',
  'ahelloworld',
  'foobarbas'
  'apple'
);

here if i search for 'o' then it should return 4 as 'o' is present in only four values

Upvotes: 0

Views: 33

Answers (3)

Majid Abbasi
Majid Abbasi

Reputation: 1531

You can use from this structure:

function array_seaech($array, $search)
    {
        $count = 0;
        foreach($array as $key => $value)
        {
            if(strpos($value, $search))
                $count++;
        }

        return $count;
    }

in this structure we check all nodes of an array and check if that string exist or not.

Upvotes: 0

Renish Khunt
Renish Khunt

Reputation: 5824

try this code this is worked for me.

<?php
$input = preg_quote('o', '~'); // don't forget to quote input string!
$data = array (
  'sayhello',
  'hellostackoverflow',
  'ahelloworld',
  'foobarbas',
  'apple'
);

$result = preg_grep('~' . $input . '~', $data);
echo count($result); // return the number of element

echo '<pre>';
print_r($result);
exit;
?>

i hope this is working for you.

Upvotes: 0

Ohgodwhy
Ohgodwhy

Reputation: 50787

An array can just be flattened to a string for all intents and purposes.

$occurences = substr_count((string)$aa, 'o');

$occurences will then be 4.

Upvotes: 0

Related Questions