tags:

views:

219

answers:

6

How can I combine these 2 array?

$array1 = array("gif" => "gif", "jpg" => "jpeg", "jpeg" => "jpeg", "png" =>"png");
$array2 = array("gif" => "0", "jpg" => "90", "jpeg" => "90", "png" => "8");

I tried

$array1 = array("gif" => "gif" => "0", "jpg" => "jpeg" => "90", "jpeg" => "jpeg" => "90", "png" =>"png" => "8");

But of course it didn't work so any help?

+2  A: 

You have two values for each key. Create a sub-array for each key with more than one value:

$ar1 = array( 'key' => array('key1','key2') );
Ilya Biryukov
+6  A: 

This seems to make more sense:

$arr = array("gif" => array("extension" => "gif", "size" => "90"),
             "jpg" => array("extension" => "jpeg", "size" => "120")

               ...
              );

echo "Extension: " . $arr['gif']['extension'] . " Size or whatever: " . $arr['gif']['size'];

To loop over it:

foreach($arr as $key => $val) {
    echo "Image Type: $key, Extension: " . $val['extension'] . ", Size: " . $val['size'];
}
karim79
+1  A: 

To build on my previous answer, you're better of using to paralell arrays:

$validTypes = array("gif" => "gif", "jpg" => "jpeg", "jpeg" => "jpeg", "png" => "png");
$quality = array("gif" => 0, "jpg" => 90, "jpeg" => 90, "png" => "png");
if (!array_key_exists($image_type, $validTypes)) {
    trigger_error("Not a valid image type", E_USER_WARNING);
    return NULL;
}

// ...

$inFunc = "imagecreatefrom" . $validTypes[$image_type];
$outFunc = "image" . $validTypes[$image_type];

// ...

$outFunc($image, $source_file, $quality[$image_type]);

karim's answer is also fine, though. Just a matter of preference.

Emil H
thanks, I ended up doing the 2 arrays, things usually come to my head right after I hit the submit button on a question
jasondavis
A: 

not sure how you want to 'combine' them. Im going to assume you want each key from the 1st array to map to a value in the 2nd

 foreach($array1 as $k=>$v)
 {
   $a3[$k] = $array2[$v]
 }

gives you

  $a3 = array('gif'=>'0', 'jpg'=>'90', 'jpeg'=>'90', 'png'=>'8');

But that is the same as array2. Maybe

 foreach($array1 as $k=>$v)
 {
   $a3[$k] = array($array1[$k],$array2[$k]);
 }

gives

 $a3 = array('gif'=>array('gif',0),'jpg'=>array('jpeg',90)...)
shimpossible
A: 

I'm surprised that none of the answers refer you to the following which could essentially be described as "everything you ever wanted to know about PHP arrays but were afraid to ask"

George Jempty
+1  A: 
$array1 = array("gif" => "gif", "jpg" => "jpeg", "jpeg" => "jpeg", "png" =>"png");
$array2 = array("gif" => "0", "jpg" => "90", "jpeg" => "90", "png" => "8");
$finalarray = (array_merge_recursive($array1,$array2));

the structure of $finalarray is:

Array
(
[gif] => Array
    (
        [0] => gif
        [1] => 0
    )

[jpg] => Array
    (
        [0] => jpeg
        [1] => 90
    )

[jpeg] => Array
    (
        [0] => jpeg
        [1] => 90
    )

[png] => Array
    (
        [0] => png
        [1] => 8
    )
)
smchacko