0

I have an array:

$array = Array
(
    [0] => qst
    [1] => insert_question_note
    [2] => preview_ans
    [3] => _preview
    [4] => view_structure_answer_preview
    [5] => index
}

I need to unset the array keys based on elements in

$array_elements_to_be_remove = array('qst','_preview'); // or any string start with '_'

I tried to use:

$array_key = array_search('qst', $array);
unset($array[$array_key]);

$array_key_1 = array_search('_preview', $array);
unset($array[$array_key_1]);

Is there any other better ways to search batch of elements in $array ?

I expect that if I can use array search like this:

$array_keys_to_be_unset = array_search($array_elements_to_be_remove, $array);

I found a way to search the string if it is start with '_' as below:

substr('_thestring', 0, 1)

Any ideas how to do that?

2 Answers 2

1

You could use array_filter

$array = Array(
    0 => 'qst',
    1 => 'insert_question_note',
    2 => 'preview_ans',
    3 => '_preview',
    4 => 'view_structure_answer_preview',
    5 => 'index'
);

$array_elements_to_be_remove = array('qst', '_preview'); // or any string start with '_'
$new_array = array_filter($array, function($item)use($array_elements_to_be_remove) {
    if (in_array($item, $array_elements_to_be_remove) || $item[0] == '_')
        return false; // if value in $array_elements_to_be_remove or any string start with '_'
    else
        return true;
});
var_dump($new_array);
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! Millions appreciated.
1

You can use php build function array_diff:

$arr=array_diff($array1, $array2);

Refer this php docs

2 Comments

Thanks, how about the string started with '_'?
I meant, to search automatically the elements contained in $array1 and push to array2

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.