S
S
Slava Kolos2015-12-18 14:50:46
PHP
Slava Kolos, 2015-12-18 14:50:46

Why is the first value not removed from the array with key 0?

for some reason, the first value is not removed from the first array

$block = array(1,2,3,4,5,6,7,8,9,10,11,12);
$bad_block = array(1,2,3);

foreach ($block as $key => $form) {
if ( array_search($form, $bad_block) ) {
unset($block[$key]);
}
}

 print_r($block);
 print_r($bad_block);


Array block
(
[0] => 1
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
[10] => 11
[11] => 12
)
Array bad_block
(
[0] => 1
[1] => 2
[2] => 3
)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey, 2015-12-18
@kolosslava

because 0 == false...
any functions that return array keys, positions in strings, etc. you need to check like this:

if(false !== array_search($form, $bad_block)) {
    // ...
}

A
Alexander N++, 2015-12-18
@sanchezzzhak

foreach ($block as $key => &$form) {
if ( array_search($form, $bad_block) ) {
unset($form);
}

The documentation for loops explains everything well.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question