1

I have arrays like this:

$actions = array(
    array(
        'type'      => 'checkbox',
        'id'        => 'f0',
        'is_active' => 1
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f1',
        'is_active' => 0
    ),
    array(
        'type'      => 'radio',
        'id'        => 'f2',
        'is_active' => 0
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f3',
        'is_active' => 1
    ),
    array(
        'type'      => 'text',
        'id'        => 'f4',
        'is_active' => 1
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f5',
        'is_active' => 0
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f6',
        'is_active' => 1
    )
);

so i need to extract the arrays that has type = 'checkbox' and is_active = 1 only without any "for loop" ..

Any good solution ?

3 Answers 3

3

You can use array_filter with callback to return only type which is checkbox.

$filtered = array_filter($array, function($v){return $v['type'] == 'checkbox' && $v['is_active'] == 1;});

Working example :- https://3v4l.org/idAR4

Sign up to request clarification or add additional context in comments.

Comments

2

Edit of answer @Rakesh Jakhar

One more condition added as per the question

<?php
// Your code here!
$actions = array(
    array(
        'type'      => 'checkbox',
        'id'        => 'f0',
        'is_active' => 1
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f1',
        'is_active' => 0
    ),
    array(
        'type'      => 'radio',
        'id'        => 'f2',
        'is_active' => 0
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f3',
        'is_active' => 1
    ),
    array(
        'type'      => 'text',
        'id'        => 'f4',
        'is_active' => 1
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f5',
        'is_active' => 0
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f6',
        'is_active' => 1
    )
);

$filtered = array_filter($actions, function($v){return $v['type'] == 'checkbox' && $v['is_active']==1 ;});
print_r($filtered);
?>

Comments

0

You also can sue array_reduce, Demo

$filtered = array_reduce($array, function($a,$b){
    if($b['type'] == 'checkbox' && $b['is_active'] == 1){
        $a[] = $b;
        return $a;
    }else{
        return $a;
    }},[]);
print_r($filtered);

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.