Monday, 2 February 2015

Trim All Members Of An Array With PHP

Trim All Members Of An Array With PHP

This little helper function provides a simple method to trim the white space from the beginning and end of all the elements in an array. It uses the call to array trim, which, in turn, calls the trim() function. The iteration is handled internally and so provides maximum performance then dealing with the the problem in user code.
Any built in PHP function can be mapped in this way, to affect all members of an array.

<?php
    
/**
    *
    * Trim all values in an array
    *
    * @param$array  array   The original array
    * @return   array   the array of trimmed values
    *
    */
    
function array_trim$array )
    {
        return 
array_map'trim'$array );
    }
?>

EXAMPLE USAGE


<?php

    $array 
= array(' dingo''wombat          ''platypus' );

    
$array array_trim$array );

    foreach( 
$array as $key=>$value )
    {
        echo 
"$key = $value<br />";
    }
?>

DEMONSTRATION

0 = dingo
1 = wombat
2 = platypus

0 comments:

Post a Comment