KunKun
KunKun

Reputation: 67

Combine two array with index number

I have 2 arrays

Array
(
    [0] => bedroom
    [1] => traditional
    [2] => farmhouse
    [3] => modern
    [4] => contemporary
)

and

Array
(
    [0] => aaaa
    [1] => bbbb
    [2] => cccc
    [3] => dddd
    [4] => eeee
    )

How can I combine the two arrays above, I want the result in a String like this...

bedroom_aaaa, traditional_bbbb, farmhouse_cccc, modern_dddd, contemporary_eee

So far I tried like this, but it does not work...

$res = array_combine ($a,$b);

                foreach($res as $r){
                  echo $res.'_'.$r.', ';
                }

Upvotes: 0

Views: 54

Answers (2)

Girish Patil
Girish Patil

Reputation: 154

This php function takes two arrays as input and checks if they have the same size. If the two arrays don't have same size then there will be error "undefined index".

function combine_array($a,$b){
    $res = [];
    if(count($a)==count($b)){
      // The count function returns the size of an array
      for($i=0;$i<count($a);$i++){
        $res[$i] = $a[$i]."_".$b[$i];
      }
      return $res;
    }
   return false;
}

Upvotes: 0

KunKun
KunKun

Reputation: 67

From your logic i found the way... Thanks

        if(count($a)==count($b)){
            for($i=0;$i<count($a);$i++){
                $res = $a[$i]." _ ".$b[$i];
                echo $res.'<br />';
            }
        }

Upvotes: 1

Related Questions