PHP split a variable separated by "|" and bring all results that are not empty

Asked

Viewed 30 times

0

I have a variable that are the footage of the building units and each unit is separated by "|" and may have up to 4 units, ex: 35|41|50|12. But it doesn’t always have 4 units, ex: 41|50||

Then I need to "break" this variable into individual variables and I thought to do with explode:

$unidades = $row->fotos;
$unidades = explode("|", $unidades);
$un0 = $unidades[0];
$un1 = $unidades[1];
$un2 = $unidades[2];
$un3 = $unidades[3];

The problem in this case is that then he brings the $photos[] empty tbm.

How can I bring only those that have some value? And also get the highest and lowest value?

In short what I need is for you to take the amount 35|41|50|12 for example and show the lowest and highest value, something like: echo $menorvalor. ' à '.$maiorvalor.'

2 answers

0

You can filter the values with the function array_filter() and its functions min() and max(), for the specific values.

Ex:

$unidades = $row->fotos;
$unidades = explode("|", $unidades);

$unidades = array_filter($unidades, 'strlen');

To get the lowest value.

$menorvalor = min($unidades);

To get the most value

$maiorvalor = max($unidades);

0

Another way is to check if the values were all received and only then put in the vector

<?php
    $unit = $_GET['unit'];
    $unidades = explode("|", $unit);
    $units = array();



    foreach ($unidades as $key => $val) {

        if( !empty( $val ) ){
            echo "Unidades Rec[" . $key . "] = " . $val . "<br>";
            $units[] = $val;
        }

    }
    sort($units);


    echo "Unidades: ".$menorvalor = min($units)." a ".$maiorvalor = max($units);



?>

Browser other questions tagged

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