Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25745

How do i remove multiple array elements in PHP?

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..

Upvotes: 0

Views: 3308

Answers (3)

Rusty Fausak
Rusty Fausak

Reputation: 7525

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]);
            }
        }
    }
}

Upvotes: 1

Andrew Moore
Andrew Moore

Reputation: 95334

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.

Upvotes: 1

user7675
user7675

Reputation:

Nested foreach, by reference.

foreach( $rules as $field => &$fieldrules ) {
    foreach( $fieldrules as $rulename => &$rulesettings ) {
        unset( $rulesettings['message'] );
    }
}

Upvotes: 2

Related Questions