Monday, April 29, 2013

Php check a value exists in multi level array and return path

Search in array using php by value if the array is any depth data.
<?php
function array_value_exists($search = "", $searchArray = array(), $returnKey = false, &$returnKeyArray = array(), $level = 0) {
    $returnValue = false;
    $search = trim(strval($search));
    if(strlen($search) == 0) {
        return false;
    }
    if(is_null($searchArray)) {
        return false;
    }
    if(!is_array($searchArray)) {
        return false;
    }
    foreach($searchArray as $key => $value) {
        array_push($returnKeyArray, $key);
        if(is_string($value)) {
            if($search == trim($value)) {
                $returnValue = true;
                break;
            }
        } else if(is_array($value)) {
            $returnValue = array_value_exists($search, $value, false, $returnKeyArray);
            if($returnValue == true) {
                break;
            }
        }
    }
    if($returnKey == true) {
        return $returnKeyArray;
    }
    return $returnValue;
}
?>

Use:<?php
$ary = array(
            "bm" => array(
                "dev" => array(
                    "pritom" => array(
                        "email" => "pritomkucse@yahoo.com"
                    ),
                    "touhid" => array(
                        "email" => "touhid@yahoo.com"
                    )
                ),
                "designer" => array(
                    "dipu" => array(
                        "email" => "dipu@yahoo.com"
                    )
                )
            ),
            "gpit" => array(
                "dev" => array(
                    "sanat" => array(
                        "email" => "sanat@gpit.com"
                    )
                )
            )
        );
        $has = array_value_exists("pritomkucse@yahoo.com", $ary);
        echo $has == true ? "True" : "False";
        print_r(array_value_exists("pritomkucse@yahoo.com", $ary, true));
?>

Output:
1. True (Find or not)
2. Path to this value.
Array
(
    [0] => bm
    [1] => dev
    [2] => pritom
    [3] => email
)

No comments:

Post a Comment