PDA

View Full Version : php explode question



centenial
10-10-2006, 02:32 AM
Hi,

I have a 'string' that contains three pieces of information. I need to put each of those pieces of information into a separate variable so I can insert them into three seperate fields in a database table.

Here is what I'm trying to do:


<?php

$string = explode(';', first,second,third);

$i=1;

foreach ($string as $variable) {
$v_$i = "$variable";
$i++;
}

// And then use $v_1, $v_2, and $v_3 as variables in a query string.

?>

Unfortunately this creates a PHP error. Does anyone know how to do this?

Thanks for your time,

djr33
10-10-2006, 02:40 AM
I'm not sure of all the technicalities, but this should fix your script:


<?php
$var = "a;b;c";
list($v_1,$v_2,$v_3) = explode(';',$var);
?>

Reasons:
1. The syntax on explode is just wrong. I don't know what you're doing there.
The first parameter is the seperator, the next is the string from which the data is coming, the next is the limit. The limit, IF needed, is an integer of how many results. That means you can control it so it only splits 1 time or 2 or 7, rather than through the entire string at every match.
2. String is an array, though, I think you know that, using foreach.
3. Why "$variable"? you don't need the quotes.... just the variable. Placing quotes around it would ensure that it's a string as opposed to, for example, an integer, but it would already be a string as output from the explode command that gets data from a string.
4. $v_$i is wrong. $$var works. So:
$name = "v_1";
$$name = "value here";

Note: I am not sure that the underscore is valid in a variable. I know it's reserved as the first character (for $_GET/$_SESSION/etc. globals). I think, though, that it's valid... just have never had the need to know.

nelis
10-10-2006, 02:47 PM
I kind of understand what the code is trying to do. You're trying to make dynamic variables depending on how big the array would be..

In djr33's example:
$var = "a;b;c";
list($v_1,$v_2,$v_3) = explode(';',$var);

if $var-"a;b;c;d";

then it would be more.. etc.. Thats where you're trying to do the $var_$i.

I would just do it this way

$var = explode(';',$string);

for($x=0;$x<count($var);$x++)
{
'do something with' $var[$x];
}

this would handle if string = "a;b;c;d;e;f;g"; .... etc..

djr33
10-10-2006, 09:43 PM
That's true.

Also, you could use a dynamically named variable in that, but using arrays might be easier.

All depends on why you are doing this.