Page 1 of 1

parse an array

Posted: Mon Dec 09, 2002 2:54 am
by soshea
well i have exhausted all of my resources here, hopefully someone can give some insight. i am writing data to a .txt file onto the local server
example data:
02-12-08 23:00 1.3 10.3
(this comes off of a sensor)
sometimes the data will have more or less spaces inbetween ie (',' represents the spaces):
02-12-08 23:00,,,,-1.3,,,,,10.3
02-12-08 23:00,,,1.5,,,,,,,11.3
02-12-08 23:00,,,,0.4,,,,,,,9.3
i am utilizing fwrite to the file so only one line of data shows at a time. the problem is that when i utilize file() to get the data from .txt and put the data into an array to grab the numbers for calculations, my structure is completely thrown off due to the extra array with a " ".
if i am grabbing 02-12-08 23:00 0.4 9.3 i am calculating the numbers 0.4 and 9.3. i know that if i utilize end() i can always grab the last array 9.3, but it is the 0.4 number that is difficult. sometimes there are 3 or 4 spaces before, and sometimes there are 3 or 4 or 5 after (basically it varies). how do i get rid of the "empty" key-val pair so that my data will endup:
key[0]02-12-08
key[1]23:00
key[2]0.4
key[4]9.3
and not
key[0]02-12-08
key[1]23:00
key[3]
key[4]
key[5]0.4
key[6]
key[7]
key[8]
key[9]9.3
sorry for the lengthy question, but i did not want to confuse anyone.
any help is greatly appreciated!! and if there are any suggestions on a different path, please advise.

Posted: Mon Dec 09, 2002 3:06 am
by dusty

Code: Select all

foreach($array as $key => $val) {
  if (empty($val)) unset($array[$key]);
}

Posted: Mon Dec 09, 2002 3:43 am
by volka
maybe I'm missing the point but
02-12-08 23:00,,,,-1.3,,,,,10.3
is a single line in your file? and you convert it (probably) with explode to an array? If so take a look at preg_split() as it offers
flags can be any combination of the following flags (combined with bitwise | operator):
PREG_SPLIT_NO_EMPTY
If this flag is set, only non-empty pieces will be returned by preg_split().
...

Posted: Mon Dec 09, 2002 9:25 am
by soshea
thanx! both worked, but i went with preg_split(). less code and it replaced my explode().
appreciate the help!!