How to "break" the PHP variable and bring separate results

Asked

Viewed 90 times

1

I’m a beginner in php.

I have these variables:

$tipo='a,b,c,d';
$metragem='15,18,32,44';

And I need him to bring

a: 15
b: 18
c: 32
d: 44

but if the values are like those below:

$tipo='a,,,';
$metragem='15,,,';

just bring

a: 15

How can I do? It’s using explode and foreach?

3 answers

4

Follow a way of doing:

// Seus dados
$tipo='a,,c,d';
$metragem='15,18,,44';
// Transformando em array
$tipo = explode(",",$tipo);
$metragem = explode(",",$metragem);
// Unindo todos arrays em 1
$arr = array($tipo,$metragem);
// Ordenando
array_unshift($arr, null);
$res = call_user_func_array("array_map", $arr);

// Imprimindo
foreach($res as $v) {
    // Se algum valor é vazio
    if($v[0] != "" && $v[1] != "") {

        echo '<br>' . $v[0] . ": " . $v[1]; 
    }
}

Exit:

a: 15
d: 44

See working on Ideone

Documentation - Explode

Merge all values at the same array level, at the same level

3

In a simplified form:

$tipo=array('a','b','c','');
$metragem=array(15,18,32,44);
for ($i=0; $i<sizeof($tipo); $i++) 
    if ($tipo[$i] <> '') echo "$tipo[$i]: $metragem[$i]<br>";

Upshot:

a: 15
b: 18
c: 32
  • Roger, if it has an empty value in $metragem=array(15,,32,44); make a mistake.

  • True, but since he did not specify the origin of the arrays nor in which situation any element will be empty, I opted for a simplified solution taking into account that only $type will be the indicator. It can replace integers with 0 in the $metragem array in a forward load to this code.

1


As commented, you can do this only with the functions array_map and explode, still with the array_filter to remove possible unwanted results:

function relacao_tipo_metragem($tipo, $metragem) {
    if ($tipo and $metragem) {
        return "{$tipo}: {$metragem}";
    }

    return null;
}

$tipo = explode(',', 'a,b,c,d');
$metragem = explode(',', '15,18,32,44');
$dados = array_filter(array_map('relacao_tipo_metragem', $tipo, $metragem));

print_r($dados);

Generating the result:

Array
(
    [0] => a: 15
    [1] => b: 18
    [2] => c: 32
    [3] => d: 44
)

If one of the values, either type or length, is not set, the column will be ignored.

  • show, gave right, then just added at the end foreach($given the $line){echo $line. '<br/>';}

  • @Leandromarzullo You can do echo join('<br>', $dados). You don’t need the noose.

Browser other questions tagged

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