Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array with empty values need to be discarded

Tags:

arrays

php

Given, In a input form user can separate some specific names by new line and i am saving those names in an array. Then I print those names and at last say something like "thank you for the names".

         $var = "name1 



name2


        ";
    $your_array = explode("\n", $var);


        for($i=0; $i<(sizeof($your_array));$i++) {
          echo ($your_array[$i]);  
        }
echo "Thank you for the names"

But the problem is if someone enter more than one newline before or after a name then the next name show after some distance like below

    name1



    name2


Thank you for the names

How can escape this and output as below

name1
name2
Thank you for the names

I tried to use array_filter() but it don't work here.

Update:

If someone input
$var = "name1\nname2\n\n\n


           name3                     


name4";

output should be like

name1
name2
               name3
name4

But all the answers show like

name1
name2
name3
name4

2 Answers

Let's use a foreach loop for the sake of simplicity...

1) We need to iterate through the new array and trim the names so we lose all whitespace.

2) We echo out the name, if and only if the length of the name is 1 or more.

3) We add on a <br> tag to make each name appear on a new line.

<?php

$var = "name1\nname2\n\n\n";

$your_array = explode("\n", $var);

foreach($your_array as $name)
{
    if(preg_match("/[a-zA-Z0-9]{1,}/i", $name)) {
        $name = trim($name);
        echo (strlen($name) > 1) ? sprintf('%s<br>', $name) : '';
    }
}

echo "Thank you for the names";
?>
like image 195
phpisuber01 Avatar answered Nov 27 '25 00:11

phpisuber01


$your_array = explode(PHP_EOL, $var);

$names = array();

for ($i = 0; $i < count($your_array); $i ++ )
{
    // trim clean spaces and newlines surrounding each line
    // resulting value is assigned to $test
    // if this value is not empty the conditional is a true proposition
    // so is assigned to $names
    if ($test    = trim($your_array[$i]))
        $names[] = $test;
}

echo implode(PHP_EOL, $names) . PHP_EOL;
echo 'Thank you for the names.';

EDIT: using foreach

$your_array = explode(PHP_EOL, $var);

foreach ($your_array as $name)
{
    if ($test    = trim($name))
        $names[] = $test;
}

if ($names)
{
    // echo implode(PHP_EOL, $names) . PHP_EOL;
    echo implode('<br />', $names) . '<br />';
    echo 'Thank you for the names.';
}
else
    echo 'Names missing.';

EDIT 2

trim accept a charlist to explicit removes, so if you want maintain spaces, make a list with newlines and carriage return only.

trim($name, "\r\n");

NOTE: PHP_EOL is the correct new line char depending of server (unix or windows).

like image 20
Igor Parra Avatar answered Nov 27 '25 01:11

Igor Parra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!