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?

  • Changing the index of the cycle for bad practice that affects performance. Check if (! Isset ($ arr [$ i + 1])) existence of the next element. - Steve

1 answer 1

 if( count($arr) % 2) array_push( $arr, null); 

And you are guaranteed to have an even number of elements in the array - beat on pairs.

If the number of elements in the array is odd, the remainder of dividing by 2 is not zero, we end up with null at the end of the array, which will get to the last key, as you wanted.

 if(( $count = count($arr)) % 2) array_push( $arr, null); for ($i = 0; $i < $count; $i+=2) { $res[$arr[$i]] = $arr[$i+1]; } 

Ideone .

  • For sure! :) Thanks @Sergiks :) - Alex