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?

Link to comment
Share on other sites

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);
  }
}
?>

Link to comment
Share on other sites

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";
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.