Jump to content

My array is reversing! why oh why!


php_joe

Recommended Posts

I am trying to write a function that will strip tags and reduce multiple line breaks & tabs to just one. There's probably a better way of doing this, but this is what I've come up with on my own.

 

This strips the tags, breaks each line into an array, separates by tabs, then removes white space.

 

function strip_whitespace($code){
$code = strip_tags($code);
$lines = explode("\n", $code);
foreach($lines as $lkey => $line){
$pieces = explode("\t", $line);
foreach($pieces as $pkey => $piece){
$newpiece[$pkey] = trim($piece);
} // end pieces
$newline[$lkey] = implode("\t", $newpiece);
$newline[$lkey] = trim($newline[$lkey]);
} // end lines
$output = implode("\n", $newline);
return($output);
}

 

However, I still end up with double tabs & double line breaks, so I tried this:

 

function strip_whitespace($code){
$code = strip_tags($code);
$lines = explode("\n", $code);
foreach($lines as $lkey => $line){
$pieces = explode("\t", $line);
foreach($pieces as $pkey => $piece){
$newpiece[$pkey] = trim($piece);
if(!$newpiece[$pkey]) unset($newpiece[$pkey]); // This reverses the array
} // end pieces
$newline[$lkey] = implode("\t", $newpiece);
$newline[$lkey] = trim($newline[$lkey]);
if(!$newline[$lkey]) unset($newline[$lkey]); // but this one works fine
} // end lines
$output = implode("\n", $newline);
return($output);
}

 

Why does the $newpiece array order reverse when I unset() the empty values?

Link to comment
https://forums.phpfreaks.com/topic/49208-my-array-is-reversing-why-oh-why/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.