Forum Moderators: coopster

Message Too Old, No Replies

PHP Array Problem

Using Explode

         

boxfan

1:44 am on Mar 21, 2007 (gmt 0)

10+ Year Member



I have the following

$BB_Basket = "basket=¦APL6007,2.00¦AVX8900,1.00¦ARCAV500,1.00";
$basket_containers = explode('¦', $BB_Basket);
unset($basket_containers[0]);
print_r($basket_containers);

This results in

Array ( [1] => APL6007,2.00 [2] => AVX8900,1.00 [3] => ARCAV500,1.00 )

Now when I try to explode further with

$basket_items = explode(',', $basket_containers);
print_r($basket_items);

This results in

Array ( [0] => Array )

This should result in a 6 item array. Any ideas what I'm doing wrong?

phpsir

2:34 am on Mar 21, 2007 (gmt 0)

10+ Year Member



try
$basket_items = explode(',', $basket_containers[1]);

boxfan

2:46 am on Mar 21, 2007 (gmt 0)

10+ Year Member



Yeah, that worked but doesn't solve the problem. I just get the first two item in the array when I'm looking for a complete array of all 6 items.

I tried to reset() the array before exploding it but that didn't work.

Any suggestions?

eelixduppy

3:19 am on Mar 21, 2007 (gmt 0)



Try something like this:

$BB_Basket = "basket=¦APL6007,2.00¦AVX8900,1.00¦ARCAV500,1.00";
$pattern = "/[¦,]/";
echo '<pre>';
print_r([url=http://www.php.net/preg-split]preg_split[/url]($pattern,$BB_Basket));
echo '</pre>';

Note: If you copy and paste the code, remember to replace the pipe character (¦) with a solid one.

Good luck! :)

boxfan

3:32 am on Mar 21, 2007 (gmt 0)

10+ Year Member



That worked perfectly, any idea why my code wasn't working?

eelixduppy

3:37 am on Mar 21, 2007 (gmt 0)



>> any idea why my code wasn't working?

explode [php.net] takes a string as a parameter, not an array. You were passing it an array and it basically wasn't doing anything with it.

To use explode, you would either have to loop through each element in the array, explode each, and then push each of those values onto another array - or - you could explode the original with ¦ as the separator, then implode the results of that with a comma, and then explode it again with a comma as the separator; way too much work! A nice preg_split does the trick nicely :)

boxfan

4:10 am on Mar 21, 2007 (gmt 0)

10+ Year Member



Thanks again and also for the explanation.