Page 1 of 1

[SOLVED]simple array question

Posted: Fri Mar 10, 2006 11:55 am
by rubberjohn
sorry if this is an obvious one but i've been working all night and my brain's fried and i can' sort this out.

i have a variable that has concatenated variables, 10 in this case. why, when i explode this into an array, does a count of the array return 11? even if i print_r there are only 10 values printed.

i'm sure i've come across this before but i cant remember how i fixed it?

any ideas??

rj

Posted: Fri Mar 10, 2006 11:57 am
by hawleyjr
Can we see some code? So we can see what your're working with :roll: :roll:

Posted: Fri Mar 10, 2006 12:07 pm
by rubberjohn
thanks for replying hawleyjr

Code: Select all

while($get_tag_name = mysql_fetch_array($sql_get_tag_name, MYSQL_ASSOC)){
	

  $var_saved_tags .= $get_tag_name[tag] . ".";
			
			

}

$array_saved_tags = explode("." ,$var_saved_tags);
if i echo $var_saved_tags i get 10 values separated by a '.' but when i explode to an array $array_saved_tags it has a count of 11 but print(_r)'s 10 values.

im not even sure if this is the right way to return an array of values into an array!! is there a better way of doing this?

thanks rj

Posted: Fri Mar 10, 2006 12:16 pm
by guided1
this is because your concatenated string will end up like this...

a.b.c.

when you explode you will get

a
b
c
[empty string]

if you add a substring($var_saved_tags,0,-1); at the end of you loop it should work fine.

edit:

a better way of doing this is inside your loop put

$array_saved_tags[] = $get_tag_name[tag]

Posted: Fri Mar 10, 2006 12:19 pm
by R4000
You should use this little function i created:

Code: Select all

function arrayClean($array) {
   foreach ($array as $index => $value) {
       if (empty($value)) unset($array[$index]);
   }
   return $array;
}
This will clean all the empty things out of your array, making it work :)

Posted: Fri Mar 10, 2006 12:38 pm
by rubberjohn
cheers guided1 and R4000 for replying

the function doesn't seem to work tho.

why does that happen when you explode a variable? would split do the same thing?

cheers

rj

Posted: Fri Mar 10, 2006 12:45 pm
by hawleyjr
Why are you not storing the data in an array to begin with?

Code: Select all

while($get_tag_name = mysql_fetch_array($sql_get_tag_name, MYSQL_ASSOC)){
   

  $var_saved_tags .= $get_tag_name[tag] . ".";

}

$array_saved_tags = explode("." ,$var_saved_tags);
To:

Code: Select all

$var_saved_tags = array();

while($get_tag_name = mysql_fetch_array($sql_get_tag_name, MYSQL_ASSOC)){

  $var_saved_tags[] = $get_tag_name[tag];

}

Posted: Fri Mar 10, 2006 12:54 pm
by rubberjohn
oh man empty square brackets - i tried that but without the empty brackets. of course thanks a lot.

i think its time to stop working for a bit now :oops: