Ankit Ankit - 15 days ago 11
PHP Question

Two Array compare with key and values in php

Please check below array I need to compare values. I have two array
one is

Array("Size"=>"Small","Color"=>"Red");


And Second Array is

Array(Array("Name"=>"Size","Value"=>"Small"),
Array("Name"=>"Color","Value"=>"Red"),
);


Now I want to compare size of first array with size of second array and color of first array with color of second array. I need both should be match. In short size should be small and color should be red. Please help Thanks in advance.

Answer

Please note that the function you are searching for is a validator.

Just coded a simple on for you :

$data      = array(
    'size' => 'small',
    'color' => 'red',
);
$validator = array(
    array(
        'name' => 'size',
        'value' => 'small',
    ),
    array(
        'name' => 'color',
        'value' => 'red',
    ),
);


function validateData(array $data, array $validator, $validateSize = false)
{
    if( $validateSize )
    {
        if( (count($data) != count($validator)) )
        {
            return false;
        }

        $found  = array_keys($data);
        $toFind = array();
        foreach($validator as $vI)
        {
            $toFind[] = $vI['name'];
        }
        $toFind = array_unique($toFind);

        if( count($found) != count($toFind) )
        {
            return false;
        }
    }

    $validate = function($name, $val) use ($validator)
    {
        $return = null;

        foreach($validator as $vItem)
        {
            if( $vItem['name'] === $name )
            {
                if( $vItem['value'] === $val )
                {
                    if($return !== false)
                    {
                        $return = true;
                    }
                }
                else
                {
                    $return = false;
                }
            }
        }

        if( is_null($return) )
        {
            $return = false;
        }

        return $return;
    };

    foreach($data as $k => $v)
    {
        if( !$validate($k, $v) )
        {
            return false;
        }
    }

    return true;
}

This will return true if you data array contains only key/value pairs allowed in $validator, false otherwise.

You can also validate that all keys are present in the data sent by setting $validateSize to true.

Hope it helped.