Array combination trouble

Hello,

I’ve having a huge hard time trying to figure out something with an array:


Array
(
    [0] => item1
    [1] => value1
    [2] => item2
    [3] => value2
)

I need it like this:


Array
(
    [item1] => value1
    [item2] => value2
)

My example has just a few elements but they can be vary from just a few to a lot of them so this has to be automated… How could I do this, please help!?

Thanks a lot.

Here you go. :slight_smile:


<?php
$array = array(
  'itemOne',
  'valueOne',
  'itemTwo',
  'valueTwo',
  'itemThree',
  'valueThree',
);

function combine($array){
  $combined = array();
  foreach(array_chunk($array, 2) as $pair){
    if(2 === count($pair)){
      list($key, $value) = $pair;
      $combined[$key] = $value;
    }
  }
  return $combined;
}

print_r(
  combine($array)
);

/*
  Array
  (
    [itemOne] => valueOne
    [itemTwo] => valueTwo
    [itemThree] => valueThree
  )
*/

It depends on the array but if the order is always the same:


$array = array('item1', 'value1', 'item2', 'value2');

$new_array = array();

foreach ($array as $k => $v)
{
    if ($k % 2 == 1) continue;
    
    if (isset($array[($k+1)])) $new_array[$v] = $array[($k+1)];
}

echo '<pre>'.print_r($new_array, 1).'</pre>';

Just for “lolz” and a spot of tinkering.


<?php
class ArrayChunkIterator extends ArrayIterator
{
  public function __construct($array, $size){
    parent::__construct(array_chunk($array, $size));
  }
}

class ArrayPairIterator extends ArrayChunkIterator
{
  public function __construct($array){
    parent::__construct($array, 2);
  }
  
  public function valid(){
    return 2 === count(parent::current());
  }
  
  public function current(){
    list($key, $value) = parent::current();
    return $value;
  }
  
  public function key(){
    list($key, $value) = parent::current();
    return $key;
  }
}

$array = array(
  'itemOne',
  'valueOne',
  'itemTwo',
  'valueTwo',
  'itemThree',
  'valueThree',
);

foreach(new ArrayPairIterator($array) as $key => $value){
  echo $key, ' => ', $value, PHP_EOL ;
}

/*
  itemOne => valueOne
  itemTwo => valueTwo
  itemThree => valueThree
*/

Thank you all very much but i think i solved it by myself after few more hours …

the array


Array
(
    [0] => item1
    [1] => value1
    [2] => item2
    [3] => value2
) 


foreach ( $array as $key => $val ) {
if ( isset($array[$key]) ) {
   $new_array[$val] = $array[$key+1];
       unset( $array[$key+1] );
   }
}

new array tadaaaaa:


Array
(
    [item1] =>value1
    [item2] => value2
)