Code Demon Code Demon - 6 months ago 14
PHP Question

add new array if array's specified sub array's value is not the same

First I have this array

$age = $request->age //laravel's input

$m_array = array(
'jason' => array(
'age' => '21',
'gender' => 'male'
),
'mechelle' => array(
'age' => '19',
'gender' => 'female'
),
'Khent' => array(
'age' => '25',
'gender' => 'male'
)
);


and then check if a specified array exist from the $m_array arrays

if(isset($m_array['jason'])):

endif


and then I want to check if each array that has a 'jason' value and its sub array named 'age' has the same value from the variable '$age' and if does not then add the same array but not the same sub array named 'age' value e.g.

$m_array['jason'] = array('age' => $age, 'gender' => 'male')


so the expected output if an array is added with the same name but not the same sub array named 'age' value will be

$m_array = array(
'jason' => array(
'age' => '21',
'gender' => male
),
'jason' => array(
'age' => '18',
'gender' => male
)
);


any ideas, help, clues, recommendations, suggestions to achieve that please?

Answer

Just check the $m_array['jason'] exists or not, if not then the add a new array into the main array.

Try adding 'jason' => array('age' => '21', 'gender' => 'male'), in the main array, you will get a message Already exist and if you run this you will be notified Array Inserted.

As per your last requirement I also check for that array has the same sub array or not, if not then add the array into the main array.

$age = '22';
$gender = 'male';
$m_array = array('jason' => array('age' => '21', 'gender' => 'male'),
                 'mechelle' => array('age' => '19', 'gender' => 'female'),
                 'Khent' => array('age' => '25', 'gender' => 'male')
                );

if(isset($m_array['jason']) && is_array($m_array['jason'])){
    if($m_array['jason']['age'] == $age && $m_array['jason']['gender'] == $gender)
        echo 'Already exist';
    else
        $m_array['jason'] = array('age' => $age, 'gender' => $gender);
}else{
    $m_array['jason'] = array('age' => $age, 'gender' => $gender);
    echo 'Array Inserted';
}

print_r($m_array);

Result:

The value age overridden.

Array
(
    [jason] => Array
        (
            [age] => 22
            [gender] => male
        )

    [mechelle] => Array
        (
            [age] => 19
            [gender] => female
        )

    [Khent] => Array
        (
            [age] => 25
            [gender] => male
        )

)

Note: The same key of an array never added, its must be override, So you will loss data. Don't do that, This is what you want. But this is not possible.