PHP: Loop through each string line in a Textarea CodeUnit 08 FEB 2011

To loop through all the string inputs entered on a new line for a textarea control is not particularly challenging and uses basic array functionality to achieve this.

To see the code in action:

//trim off excess whitespace off the whole
$text = trim($_POST['textareaname']);

//explode all separate lines into an array
$textAr = explode("\n", $text);

//trim all lines contained in the array.
$textAr = array_filter($textAr, 'trim');

//loop through the lines
foreach($textAr as $line){
echo "$line";


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.

  • Surely, a little typo cropped in there — should read

    //trim all lines contained in the array.
    $textAr = array_filter($textAr, ‘trim’);

  • Ryan

    I think I found another typo, I belive

    echo “$text”;

    should be

    echo “$line”;

    • Yes, yes, I’ll fix it properly. Sheesh, as if I don’t have enough on my plate already with little Jessica! :P

  • avi

    didnt work for me, however i changed explode(“n”, $text); to explode(“n”, $text);