Creating a list from an explode()

I have a variable that’s created from a file_read_contents() before being created into an array using explode(). From there, I threw it into a FOREACH where I’m trying to use a condition that says “IF SPACE FOUND, DISREGARD” and as usual, it’s not working. :frowning:

So here’s the code:

echo '<ul>';
foreach($array as $v){
	if($v !== ''){
		echo '<li>'.$v.'</li>';
	}
}
echo '</ul>';

Any idea what I’m doing wrong here?

What do you mean by:

IF SPACE FOUND, DISREGARD

Do you mean don’t output the spaces? Don’t output if the item is only a space? Don’t output if a space is found inside the string?

try !empty($v) instead of $v !== ‘’

What space you mean? It seems that you are checking empty. Did you try empty() function for that if you really mean empty check?


if(!empt($v)){

}

Otherwise if you mean a space then try regex:


//Untested
if(!preg_match('/\\s/', $v)){

}

Something like above

Good point, Jake.

Basically, I want to avoid outputting any list-item (<LI></LI>) if what’s to be contained within, in essence, is blank. For example, right now, it’s producing a final list-item at the end that has nothing in it (true, it is an empty string–so there IS something inside it, but for all intents and purposes, it’s pragmatically blank or nothingness). So to that end, I believe that it’s a new-line character that’s causing this. The empty string consists of 1 character-long data and I had thought that trying to target ‘’ would trip the condition but it’s not…

Any suggestions?

Thanks for the input, guys. The following seemed to get it for me (and as always, feel free to provide a better method if you know of one):


!preg_match("/^\\s$/", $v)

Did you try array_filter?

Would it be more efficient or “modular” to use that?

I would prefer to clean the array prior to processing. Not sure if it’s better or not, would just be my coding practice.

Is the array coming from a DB? If so I would leave out the empties at that step in the process.

Guess the question I would be asking… Where are these empty elements coming from?

Both empty and [url=http://php.net/array_filter]array_filter* would eliminate more than “just spaces”. Admittedly, the only real trouble would be with lines containing (only) a zero character (0) but even that is more than just space.

One thing that I have used lots before would be to trim the line (even specifying just the space character if necessary) in the condition. Another more involved idea would be to change your approach to getting the lines in the first place. The [url=http://php.net/file]file function will read the lines into an array (like your file_get_contents and explode combination) and it can be instructed† to skip empty lines by using both of the FILE_IGNORE_NEW_LINES and FILE_SKIP_EMPTY_LINES flags together.

* array_filter of course can filter out “just spaces” if you tell it to.
† See the example of using the file function.