Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you strip whitespace from an array using PHP?

Tags:

php

I was wondering how can I strip white space from an array using PHP?

like image 444
ota Avatar asked Aug 01 '10 22:08

ota


People also ask

How do you remove spaces from an array?

you can do this easily if you convert the array to a List. now, use a For Each loop to access each element of the list to check for spaces. If you want to remove leading and trailing spaces in the elements that already have a value, use of for each loop is ideal to check each individually.

How can I remove a specific item from an array PHP?

In order to remove an element from an array, we can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically automatically.

How do you strip whitespace or other characters from the beginning and end of a string?

Use the . strip() method to remove whitespace and characters from the beginning and the end of a string. Use the . lstrip() method to remove whitespace and characters only from the beginning of a string.


2 Answers

You can use a combination of

  • array_filter — Filters elements of an array using a callback function
  • array_map — Applies the callback to the elements of the given arrays
  • trim — Strip whitespace (or other characters) from the beginning and end of a string

Code:

array_filter(array_map('trim', $array));

This will remove all whitespace from the sides (but not between chars). And it will remove any entries of input equal to FALSE (e.g. 0, 0.00, null, false, …)

Example:

$array = array(' foo ', 'bar ', ' baz', '    ', '', 'foo bar');
$array = array_filter(array_map('trim', $array));
print_r($array);

// Output
Array
(
    [0] => foo
    [1] => bar
    [2] => baz
    [5] => foo bar
)
like image 66
Gordon Avatar answered Sep 23 '22 04:09

Gordon


Your question isn't very clear, so I will try to cover almost all cases.

In general, you need to create a function which will do what you need, be it removing the spaces from the left and right of each element or remove the whitespace characters completely. Here's how:

<?php

function stripper($element)
{
    return trim($element); // this will remove the whitespace
                           // from the beginning and the end
                           // of the element
}

$myarray = array(" apple", "orange ", " banana ");
$stripped = array_map("stripper", $myarray);
var_dump($stripped);

?>
Result:

Array
(
    [0] => "apple"
    [1] => "orange"
    [2] => "banana"
)

You can take it from here.

like image 29
Anax Avatar answered Sep 24 '22 04:09

Anax