note 121777 deleted from function.array-search by crell

From: Date: Thu, 31 Mar 2022 20:39:43 +0000
Subject: note 121777 deleted from function.array-search by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-217952@lists.php.net to get a copy of this message
Note Submitter: t-fav ---- Noted some interesting behaviour when using array_search to find the correct index in an array containing an index with a value of 0. The following works as expected. <?php $dataSet = []; $dataSet[] = ['name' => 'Row A', 'items' => ['ItemA' => 1, 'ItemB' => 2]]; $dataSet[] = ['name' => 'Row B', 'items' => ['ItemA' => 1, 'ItemB' => 2]]; $rows = []; foreach ($dataSet as $dataRow) { $row = [ $dataRow['name'], 'ItemA', 'ItemB' ]; foreach ($dataRow['items'] as $key => $value) { $index = array_search($key, $row); $row[$index] = $value; } $rows[] = $row; } print_r($rows); It returns: Array ( [0] => Array ( [0] => Row A [1] => 1 [2] => 2 ) [1] => Array ( [0] => Row B [1] => 1 [2] => 2 ) ) However, the following seems to totally ignore the index containing the value 0 and thus returns the wrong index. <?php $dataSet = []; $dataSet[] = ['name' => 'Row A', 'items' => ['ItemA' => 1, 'ItemB' => 2]]; $dataSet[] = ['name' => 'Row B', 'items' => ['ItemA' => 0, 'ItemB' => 2]]; $rows = []; foreach ($dataSet as $dataRow) { $row = [ $dataRow['name'], 'ItemA', 'ItemB' ]; foreach ($dataRow['items'] as $key => $value) { $index = array_search($key, $row); $row[$index] = $value; } $rows[] = $row; } print_r($rows); It returns: Array ( [0] => Array ( [0] => Row A [1] => 1 [2] => 2 ) [1] => Array ( [0] => Row B [1] => 2 [2] => ItemB ) ) However, setting ItemA's value on Row B to '' or false works fine. Also, passing in the third optional parameter [, bool $strict = true ] works correctly as well. Is this intentional behaviour?

« previous php.notes (#217952) next »