0

I have an array

$rules = array(
    'name' => array(
        'isRequired' => array(
            'message' => 'Name Required'
         ),
        'isBetween' => array(
              'value' => array(5,15),
              'message' => 'Between 5 to 15 characters'
        ),
        'isAlphaLower' => array(
            'message' => 'Should be Alpha lower'
        ),
        'isLength' => array(
            'value' => 20,
            'message' => 'Length should be 20 chracters'
        )
    ),
    'email' => array(
        'isEmail' => array(
            'message' => 'Email should be valid'
        ),
        'isRequired' => array(
            'message' => 'Email Required'
        ),
    ),
    'pPhone' => array(
        'isNumber' => array(
            'message' => 'Only Numbers'
        )
    )
);

I need to remove all array element with key name message. how do i do that?

thank you..

3 Answers 3

2

Nested foreach, by reference.

foreach( $rules as $field => &$fieldrules ) {
    foreach( $fieldrules as $rulename => &$rulesettings ) {
        unset( $rulesettings['message'] );
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

i did it this way, but was wondering if there is any inbuilt php function which could allow me to unset the way i want :)
There is no built-in PHP function to do what you are asking.
Nope, I don't believe there's a "deep unset keys matching this key name" function.
1

Use unset() within a nested foreach loop:

foreach($rules as &$fieldrules)
  foreach($fieldrules as &$ruleparams)
    if(isset($ruleparams['message'])) // E_STRICT
      unset($ruleparams['message']);

Note the & before the variables. This is a pass by reference. It's important to do so here so that we modify the actual array and not a copy.

Comments

1

If you are tring to remove all key/value pairs where the key is 'message' three levels deep, you could try the following:

foreach ($rules as $k1 => $arr) {
    foreach ($arr as $k2 => $arr2) {
        foreach ($arr2 as $k3 => $arr3) {
            if ($k3 == 'message') {
                unset($rules[$k1][$k2][$k3]);
            }
        }
    }
}

Comments

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.