error_reporting(E_ALL); // - Обязательно
There is a numeric array with an even number of keys (and how many there are in general is not known in advance):
$arr = ['0'=>'value1', '1'=>'value2', '2'=>'value3', '3'=>'value4'];
The task is to get:
Array ( [value1] => value2 [value3] => value4 )
I do this:
$count = count($arr); for ($i = 0; $i < $count; $i++) { $res[$arr[$i]] = $arr[++$i]; }
And everything seems to be ok, but when an array with an odd number of keys:
$arr = ['0'=>'value1', '1'=>'value2', '2'=>'value3'];
The task is to get an array of the form:
Array ( [value1] => value2 [value3] => )
And here in 'value3'=>''
- not skipped 2
, but it should be null
I do the same, just adding a crutch in the form of @
:
$count = count($arr); for ($i = 0; $i < $count; $i++) { @$res[$arr[$i]] = $arr[++$i]; }
And without @
, an error will be displayed:
Notice: Undefined offset ...
The result is what you need:
Array ( [value1] => value2 [value3] => )
That's just the use of @
- I am very confused. How can this be avoided?