Home > Mobile >  How to add string if two arrays are in php?
How to add string if two arrays are in php?

Time:03-04

I have array values if there are two values i need to add a string "AND" if single value "AND" string should not be added. i have tried with the following code. cant get the required output

$unserialize_meta = array(0=>"Alcor",1=>"President",2=>"Treasurer");
$checks = array();
foreach($unserialize_meta as $meta){
    $checks[]= $meta;
}

echo implode(" And ",$checks);

Output:

Alcor And President
Alcor And President And

required output:
Alcor And President
Alcor And President 

CodePudding user response:

You can use the implode function for this. Details can be found here.

Considering the above code:

$unserialize_meta = array(0=>"Alcor",1=>"President",2=>"Treasurer");
$checks = implode(" AND ", array_filter($unserialize_meta));
var_dump($checks);

The array_filter will remove any empty values in the array.

CodePudding user response:

I thing you don't need to loop array. you just need to implode array with the string. Please try below code it will add string AND with your array values.

$unserialize_meta = array(0=>"Alcor",1=>"President",2=>"Treasurer");
if(!empty($unserialize_meta )) {
    echo implode(" And ",$unserialize_meta);
}

Output:

Alcor And President And Treasurer

CodePudding user response:

There is mistake saved in array values in array I'm getting empty array. So I add a empty array check :

if(!empty($meta)){
    $checks[]= $meta;
}
  • Related