Home > OS >  Addaing a value to an existing key in associative array
Addaing a value to an existing key in associative array

Time:02-28

So I'm trying to add a value to an existing key in an associative array. Key 'message' is for displaying different errors based on validation.

$formStatus = [
        'success' => false, 
        'message' => "Phone number validation failed"
    ];

I want to add another message later, on the same key, if lets say email validation fails. Is this even possible ?

CodePudding user response:

you can also use **array_replace()** function

$formStatus = [
        'success' => false, 
        'message' => "Phone number validation failed"
        ];
        print_r($formStatus); //printing array for checking

        $formStatus = array_replace($formStatus, array("message" => "Email validation failed"));

        print_r($formStatus); //printing array for checking

CodePudding user response:

You can change $formStatus like this:

        $formStatus = [
        'success' => false,
        'validation' => [
            'phone_message' => 'Phone number validation failed',
            'email_message' => 'Email validation failed',
        ]
    ];
  • Related