Jump to content

Not let explode put blanks into the array?


galvin

Recommended Posts

I have strings that can look like this "monkeys / cats/ dogs / snakes".

 

I have code that breaks the items apart and puts each as a separate item into an array, like this (where $getstring['thestring'] equals strings like the example given above)...

 

$array = explode("/", strtolower(trim($getstring['thestring'])));
			foreach($array as $k=>$v)
			{
			$array[$k] = trim($v);
			}
		}

 

My question is how can I add some code so that if there are ever instances where there is nothing between  each /, it does NOT put that "blank" into the array?

 

For example, if a string was something like "monkeys / cats/ / dogs/ eagles / / snakes", the code now would create two array items that are essentially "blank" because there were two consecutive slashes, two different times in that same string.

 

These strings are entered by users so there is definitely a possibility they make a mistake such as above so I need a way to weed out those mistakes (i.e. the blanks).

 

Any ideas for easiest way to find the "blanks" and NOT have them in the array?

The first thing I can think of is simply wrapping the $array[$k] = trim($v); into an if (trim($v) != "")

Alternatively you could split the string using preg_split instead of explode, but I don't know what the regexp would have to look like

 

--edit--

I just noticed that the if statement alone wouldn't work. Instead:

<?php
foreach($array as $k=>$v) {
  if (trim($v) == 0) {
    unset($array[$k]);
  } else {
    $array[$k] = trim($v);
  }
}
?>

It's only necessary if you rely on the array keys later in your code. If you don't, forget about it.

<?php
//original array
$fruit[0] = "pear";
$fruit[1] = "banana";
$fruit[2] = "";
$fruit[3] = "apple";

//array after removing empty element
$fruit[0] = "pear";
$fruit[1] = "banana";
$fruit[3] = "apple";

//array after re-indexing
$fruit[0] = "pear";
$fruit[1] = "banana";
$fruit[2] = "apple";
?>

You don't need to use any loops to do this:

<?php
$str = "monkeys / cats/ / dogs/ eagles / / snakes";
$ary = array_values(array_filter(array_map('trim',$ary)));
echo '<pre>' . print_r($ary,true) . '</pre>';
?>

 

Look up array_map(), array_filter(), and array_values().

 

Ken

 

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.