comma between the arrays

Asked

Viewed 50 times

2

I am bringing the following information from a form:

$seg = "Seg";
$ter = "Ter";
$qua = "Qua";
$qui = "Qui";

Only in many cases, some of these fields will come empty, ex.:

$seg = "Seg";
$ter = "Ter";
$qua = "";
$qui = "Qui";

I’d like to take this information and put a comma between the words, like this:

Seg,Ter,Qui

I tried it this way, but it didn’t work:

$diasPromocoes = $seg.",".$ter.",".$qua.",".$qui;
$dividir = explode(",",$diasPromocoes); 
echo implode(",",$dividir);

Is returning:

Seg,Ter,,Qui

3 answers

1


$diasPromocoes = array($seg,$ter,$qua,$qui);

// O array_filter com callback vai limpar os campos vazios do array
$diasPromocoes = array_filter($diasPromocoes, function($item){ 
    return !empty($item);
});

echo implode(',', $diasPromocoes);

0

Place variables in an array and do the implode.

Example

<?php

$arr = ['Segunda', 'Terça', 'Quarta', 'Sexta'];

echo implode(',', $arr);

0

You can turn the variables into an array and use the function array_filter:

$diasPromocoes = array($seg,$ter,$qua,$qui);
$arrayLimpa = array_filter($diasPromocoes);
echo arrayLimpa;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.