Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Array Functions : array_combine

array_combine

Creates an array by using one array for keys and another for its values (PHP 5)
array array_combine ( array keys, array values )

Example 235. A simple array_combine() example

<?php
$a
= array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

The above example will output:

Array
(
   [green]  => avocado
   [red]    => apple
   [yellow] => banana
)

Related Examples ( Source code ) » array_combine


Code Examples / Notes » array_combine

wiebe

When you have not the use off PHP 5.
The workaround off  'Ivo van Sandick' can be much shorter.
I use my function:
<?
// combine $arr with $arr_to_key where $arr_to_key becomes key of $arr.
function array_comb($arr, $arr_to_key){
         $i = 0;
         foreach($arr_to_key AS $value){
                 $arr_combined[$value] = $arr[$i];
                 $i++;
         }
         RETURN $arr_combined;
}
//example.
$arr_1[0] = 'apple';
$arr_1[1] = 'banana';
$arr_2[0] = 'green';
$arr_2[1] = 'yellow';
$arr_comb = array_comb($arr_1, $arr_2);
//$arr_comb['green'] = 'apple'
//$arr_comb['yellow'] = 'banana'
?>


ifeghali

Use that code to group an array by its first element.
<?
function groupbyfirst($array)
{
foreach ($array as $row)
{
$firstkey = array_keys($row);
$firstkey = $firstkey[0];
$key = $row[$firstkey];
unset($row[$firstkey]);
$newarray[$key][] = $row;
}
return $newarray;
}
?>
Example:
<?
$array =
Array(
0 => Array('color' => 'red','name' => 'apple', 'quantity' => '3'),
1 => Array('color' => 'green','name' => 'pear', 'quantity' => '2'),
2 => Array('color' => 'yellow','name' => 'corn', 'quantity' => '3'),
3 => Array('color' => 'blue','name' => 'grape', 'quantity' => '4'),
4 => Array('color' => 'yellow','name' => 'banana', 'quantity' => '13'),
);
$output = groupbyfirst($array);
print_r($output);
?>
will return:
Array
(
[red] => Array ( [0] => Array ( [name] => apple [quantity] => 3 ) )
[green] => Array ( [0] => Array ( [name] => pear [quantity] => 2 ) )
[yellow] => Array ( [0] => Array ( [name] => corn [quantity] => 3 ), [1] => Array ( [name] => banana [quantity] => 13 ) )
[blue] => Array ( [0] => Array ( [name] => grape [quantity] => 4 ))
)
Or you can use mysql recordset:
<?
while ($row=mysql_fetch_array($result,MYSQL_ASSOC))
{
$firstkey = array_keys($row);
$firstkey = $firstkey[0];
$key = $row[$firstkey];
unset($row[$firstkey]);
$newarray[$key][] = $row;
}
?>


toth dot janas

Under this note i send yesterday a function that in array show once the dupicated elements. Sorry, the function is wrong. I corrected the error and i write a new function is working right.
/tested/.
The test array is:
$test = array(
0 => 1,
1 => 2,
2 => 1,
3 => 3,
4 => 4,
5 => 2,
6 => 5,
7 => 4
);
the function:
function array_no_duplicate($array_tmb){
$temp = array();
foreach ($array_tmb as $value){
$if_one = 0;
    foreach ($temp as $new_value) {
if($new_value == $value)  $if_one = 1;
}
if($if_one == 0)  array_push($temp, $value);
   }
return $temp;
}
example:
var_dump(array_no_duplicate($test));
this output will show array without duplicated elements.
Good work!


khaly

This is the fonction for PHP4 :
function array_combine($arr1,$arr2) {
  $out = array();
  foreach($arr1 as $key1 => $value1) {
$out[$value1] = $arr2[$key1];
  }
  return $out
}


aidan

This functionality is now implemented in the PEAR package PHP_Compat.
More information about using this function without upgrading your version of PHP can be found on the below link:
http://pear.php.net/package/PHP_Compat


royanee

This correctly accounts for the error conditions, and actually works. The previous note appears to set all the values in the result array to the value of the last item in the values input array.
<?php
function array_combine( $keys, $values )
{
  if( !is_array($keys) || !is_array($values) || empty($keys) || empty($values) || count($keys) != count($values) )
  {
     trigger_error( "array_combine() expects parameters 1 and 2 to be non-empty arrays with an equal number of elements", E_USER_WARNING );
     return false;
  }
  $keys = array_values($keys);
  $values = array_values($values);
  $result = array();
  foreach( $keys as $index => $key )
  {
     $result[$key] = $values[$index];
  }
  return $result;
}
?>


q1712

there was one exaple missing in my priviouse post:
<?php
print_r( array(array()), array("array()") );
?>
prints:
Array
(
   [Array] = array()
)
@admin: please merge these 2 posts


ivo van sandick

Such a useful function, and only since version 5! Why an emulation for earlier PHP versions has not been posted long ago, is a mystery:
<?php
function array_combine_emulated( $keys, $vals ) {
$keys = array_values( (array) $keys );
$vals = array_values( (array) $vals );
$n = max( count( $keys ), count( $vals ) );
$r = array();
for( $i=0; $i<$n; $i++ ) {
 $r[ $keys[ $i ] ] = $vals[ $i ];
}
return $r;
}
?>


neoyahuu

Some tips for merging same values in an array
<?php
$array1 = array(1,2,3,4,5,6,7,8,9,10,11,12);
$array2 = array(1,2,3,13);
$merged = array_merge($array1,$array2);
// output normal array_merge
echo '<pre>After array_merge :
';
print_r($merged);
echo '</pre>';
// do double flip for merging values in an array
$merged = array_flip($merged);
$merged = array_flip($merged);
// Output after
echo '<pre>After Double Flip :
';
print_r($merged);
echo '</pre>';
?>
Output ::
After array_merge :
Array
(
   [0] => 1
   [1] => 2
   [2] => 3
   [3] => 4
   [4] => 5
   [5] => 6
   [6] => 7
   [7] => 8
   [8] => 9
   [9] => 10
   [10] => 11
   [11] => 12
   [12] => 1
   [13] => 2
   [14] => 3
   [15] => 13
)
After Double Flip :
Array
(
   [12] => 1
   [13] => 2
   [14] => 3
   [3] => 4
   [4] => 5
   [5] => 6
   [6] => 7
   [7] => 8
   [8] => 9
   [9] => 10
   [10] => 11
   [11] => 12
   [15] => 13
)


toth dot janas

If you have an array and include duplicated element, and you want to that this element just show once in array, then this function is very good solution.
function array_no_duplicate($array_tmb){
$new_array = array();
for($i = 0; $i < count($array_tmb); $i++){
$van = 0;
for($j = 0; $j < count($array_tmb); $j++){
if( $new_array[$j] == $array_tmb[$j]) $van = 1;
}
if($van == 0){
$new_array[$i] = $array_tmb[$i];
}else continue;
}
return $new_array;
}


q1712

If a value is existing twice in the $keys-array the last one overwrites the others, wich makes the returned array shorter than the given once, as usual.
If a value of the values-array is double/float, bool or array the string representaion is used, not the integer representation as usual.
<?php
print_r(
 combine(
   array('a', 'a', 'a', 0, false, 1, true, 2, 7/3),
   array("first 'a'", "second 'a'", "third 'a'", "0", "false", "1", "true", "2", "7/3")
 )
);
print_r(
 array ('a' => "first 'a'", 'a' => "second 'a'", 'a' => "third 'a'", 0 => "0", false => "false", 1 => "1", true => "true", 2 => "2", 7/3 => "7/3")
);
?>
prints:
Array
(
   [a] => third 'a'
   [0] => 0
   [] => false
   [1] => true
   [2] => 2
   [2.33333333333] => 7/3
)
Array
(
   [a] => third 'a'
   [0] => false
   [1] => true
   [2] => 7/3
)


fred

I read many workaround functions for users with php < 5
Here is mine (the simpliest I think) :
<?php
function array_combine($keys, $values) {
$result = array() ;
while( ($k=each($keys)) && ($v=each($values)) ) $result[$k[1]] = $v[1] ;
return $result ;
}
?>


muppis

I found these workarounds for PHP 4.4.x non-working with $_POST and $_GET arrays except Ivo van Sandick's one. Works well, even my client ISP denies to update to 4.4.7 at least..

chriswillarddesign

Here is my take on the combine function for PHP < 5:
<?
// Combines two associate arrays by making a array with the key being $a1 and the value $a2.
function array_combine($a1,$a2)
{
for($i=0;$i<count($a1);$i++)
$ra[$a1[$i]] = $a2[$i];
if(isset($ra)) return $ra; else return false;
}
?>


hayley watson

Fred's code just previous isn't the simplest, given...
<?php
function array_combine($keys, $values)
{
$result = array();
foreach(array_map(null, $keys, $values) as $pair)
$result[$pair[0]]=$pair[1];
return $result;
}
?>
...if you're equally happy to avoid any sort of error checking of course.


robertark

All of those 'array_combine' emulators did -not- work for me, so I created one of my own, out randomly, and it worked for me, maybe you can give it a shot and let me know how it works. Thanks..
function array_combine($arr1, $arr2)
{
 $buffer = array();
 foreach($arr1 as $key1 => $arr_1)
 {
   foreach($arr2 as $key2 => $arr_2)
     $buffer[$arr_1] = $arr_2;
 }
 return $buffer;
}


Change Language


Follow Navioo On Twitter
array_change_key_case
array_chunk
array_combine
array_count_values
array_diff_assoc
array_diff_key
array_diff_uassoc
array_diff_ukey
array_diff
array_fill_keys
array_fill
array_filter
array_flip
array_intersect_assoc
array_intersect_key
array_intersect_uassoc
array_intersect_ukey
array_intersect
array_key_exists
array_keys
array_map
array_merge_recursive
array_merge
array_multisort
array_pad
array_pop
array_product
array_push
array_rand
array_reduce
array_reverse
array_search
array_shift
array_slice
array_splice
array_sum
array_udiff_assoc
array_udiff_uassoc
array_udiff
array_uintersect_assoc
array_uintersect_uassoc
array_uintersect
array_unique
array_unshift
array_values
array_walk_recursive
array_walk
array
arsort
asort
compact
count
current
each
end
extract
in_array
key
krsort
ksort
list
natcasesort
natsort
next
pos
prev
range
reset
rsort
shuffle
sizeof
sort
uasort
uksort
usort
eXTReMe Tracker