0

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 
6
  • BTW, you can replace the loop with $checks = array_values($unserialize_meta); Commented Mar 3, 2022 at 18:02
  • Why isn't Treasurer in your expected output? Commented Mar 3, 2022 at 18:02
  • 3
    Now I see you're already using implode(). You shouldn't be getting an extra AND unless there's an empty value in the array., Commented Mar 3, 2022 at 18:11
  • 3
    You also shouldn't get two lines of output, you just have a single echo. There must be more that you're not showing us. Commented Mar 3, 2022 at 18:11
  • 3
    Alcor And President And means there are 3 values and last one is empty string/null Commented Mar 3, 2022 at 18:14

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.