2
<?php
static $cnt=0;
$name='victor';
$coll = array(
    'dep1'=>array(
        'fy'=>array('john','johnny','victor'),
        'sy'=>array('david','arthur'),
        'ty'=>array('sam','joe','victor')
    ),
        'dep2'=>array(
        'fy'=>array('natalie','linda','molly'),
        'sy'=>array('katie','helen','sam','ravi','vipul'),
        'ty'=>array('sharon','julia','maddy')
    )
    );

    function array_find($name,$arr)
    {
        global $cnt;
    if(!(is_array($arr)))
        return false;

    foreach($arr as $val)
    {
        if(is_array($val))
        array_find($name,$val);
        else
        {
        $val=strtolower($val);
        $item=strtolower($name);
        if($val==$name)
            $cnt+=1;
        }
    }
    }

    array_find($name,$coll);

    if($cnt==0)
    echo "$name was Not Found";
    else
    echo "$name was found $cnt times.";
11
  • what is your question ? Commented Mar 7, 2014 at 6:05
  • want to search a name and count the repetitions. Commented Mar 7, 2014 at 6:06
  • victor was found 2 times. isn't that right ? Commented Mar 7, 2014 at 6:07
  • and 1st of all, how the hell to edit that code. i've wasted an hour or so and still couldn't get with it !! Commented Mar 7, 2014 at 6:07
  • @ShankarDamodaran yup !! Commented Mar 7, 2014 at 6:08

1 Answer 1

1

Try this code, hope it will work

<?php
static $cnt = 0;
$name = 'victor';
$coll = array(
    'dep1' => array(
        'fy' => array('john', 'johnny', 'victor'),
        'sy' => array('david', 'arthur'),
        'ty' => array('sam', 'joe', 'victor')
    ),
    'dep2' => array(
        'fy' => array('natalie', 'linda', 'molly'),
        'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
        'ty' => array('sharon', 'julia', 'maddy')
    )
);

function recursive_search(&$v, $k, $search_query){
    global $cnt;
    if($v == $search_query){
        ++$cnt;
    }
}
array_walk_recursive($coll, 'recursive_search' , $name);
if ($cnt == 0)
    echo "$name was Not Found";
else
    echo "$name was found $cnt times.";

DEMO

Sign up to request clarification or add additional context in comments.

2 Comments

yes, that is very helpful. Now how could i get the intermediate array name i.e. whether the name was found in "dep1" or "dep2" ?
sry but i think u didn't got me right. i need to find the sub array name in which the name(s) was found. like victor was found in "dep1,dep2" sorry again if this que is pretty stupid to be asked :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.