phparraysfetchall

Combine multiple array but when one array is empty not show anything in php


I need help about combine multiple array from database and fetch with

fetchAll(PDO::FETCH_ASSOC)

first I look for data member with percentage of 90% and every data in search in database in subtract one column in query "SELECT", for example like this :

$query1 = "SELECT * FROM tb_member WHERE category = '1' AND gender = 'M' AND age = '30'";
$stmt1 = $this->db->prepare($query1);
$stmt1->execute();
$data1 = $stmt1->fetchAll(PDO::FETCH_ASSOC);

$query2 = "SELECT * FROM tb_member WHERE category = '1' AND age = '30'";
$stmt2 = $this->db->prepare($query2);
$stmt2->execute();
$data2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);

$query3 = "SELECT * FROM tb_member WHERE category = '1' AND gender = 'M'";
$stmt3 = $this->db->prepare($query3);
$stmt3->execute();
$data3 = $stmt3->fetchAll(PDO::FETCH_ASSOC);

And I combine the array with a sample code like this

$data = $data1 + $data2 + $data3;

I have tried and succeeded, but when one of the array is empty or unread it will error or not display any data even notification error

And i try make "if and else" like this

if(empty($data1)){
    $data = $data2 + $data3;
}
elseif(empty($data2)){
    $data = $data1 + $data3;
}
elseif(empty($data3)){
    $data = $data1 + $data2;
}
else{
    $data = $data1 + $data2 + $data3;
}

And page not show anything or blank, is there any other solution to solve this problem ?

UPDATE

After all i use array_merge() to combine multiple array from @Saral and when some variable is empty i use code sample like this

if(empty($array)){
    $array = array();
}

And then it's work, thank you.


Solution

  • You combine array like this

    $data = array_merge($data1, $data2, $data3);
    

    For example,

    $array1 = [];
    $array2 = ['a', 'b'];
    $array3 = ['l', 'k', 'm'];
    $array4 = [];
    
    $array = array_merge($array1, $array2, $array3, $array4);
    
    print_r($array);
    
    Output:
    Array ( [0] => a [1] => b [2] => l [3] => k [4] => m )
    

    It's weird that $array = $array1+$array2+$array3+$array4; gave me Array ( [0] => a [1] => b [2] => m )