Connecting Tech Pros Worldwide Forums | Help | Site Map

PHP String Thing

Trevor
Guest
 
Posts: n/a
#1: Jul 17 '05
Say I've got this:

<?php

$string = "Bill,Martin,Joe";
$name1
$name2
$name3

?>

How do I make the $name1 equal to the first name in the list of
strings, $name2 the second and so on?

Thank You,
Trevor


Duyet The Vo
Guest
 
Posts: n/a
#2: Jul 17 '05

re: PHP String Thing


$string = "Bill,Martin,Joe";

list ($name1,$name2,$name3) = split ( ",", $string );

"Trevor" <trevordixon@gmail.com> wrote in message
news:1108280762.365123.210860@l41g2000cwc.googlegr oups.com...[color=blue]
> Say I've got this:
>
> <?php
>
> $string = "Bill,Martin,Joe";
> $name1
> $name2
> $name3
>
> ?>
>
> How do I make the $name1 equal to the first name in the list of
> strings, $name2 the second and so on?
>
> Thank You,
> Trevor
>[/color]


Dave Patton
Guest
 
Posts: n/a
#3: Jul 17 '05

re: PHP String Thing


"Trevor" <trevordixon@gmail.com> wrote in
news:1108280762.365123.210860@l41g2000cwc.googlegr oups.com:
[color=blue]
> Say I've got this:
>
><?php
>
> $string = "Bill,Martin,Joe";
> $name1
> $name2
> $name3
>
> ?>[/color]

OK, we'll say that you have a PHP script that has one line
of code followed by three lines with parse errros ;-)
[color=blue]
> How do I make the $name1 equal to the first name in the list of
> strings, $name2 the second and so on?[/color]

http://www.php.net/manual/en/ref.strings.php
http://www.php.net/manual/en/function.explode.php

--
Dave Patton
Canadian Coordinator, Degree Confluence Project
http://www.confluence.org/
My website: http://members.shaw.ca/davepatton/
dourdoun
Guest
 
Posts: n/a
#4: Jul 17 '05

re: PHP String Thing


Simple Answer:

<?php
$string = "Bill,Martin,Joe";
list($name1, $name2, $name3) = explode(",", $string);
?>

Complicated, for any number of varibles:

<?php
$string = "Bill,Martin,Joe";
$names = explode(",", $string);

for($i = 0; $i < count($names); $i++)
{
eval('$name'.($i+1).' = "'.$names[$i].'";');
}

print $name1; // Prints 'Bill'
print $name2; // Prints 'Martin'
print $name3; // Prints 'Joe'
?>

hope it helps,

Vasilis



"Trevor" <trevordixon@gmail.com> wrote in message news:<1108280762.365123.210860@l41g2000cwc.googleg roups.com>...[color=blue]
> Say I've got this:
>
> <?php
>
> $string = "Bill,Martin,Joe";
> $name1
> $name2
> $name3
>
> ?>
>
> How do I make the $name1 equal to the first name in the list of
> strings, $name2 the second and so on?
>
> Thank You,
> Trevor[/color]
Janwillem Borleffs
Guest
 
Posts: n/a
#5: Jul 17 '05

re: PHP String Thing


dourdoun wrote:[color=blue]
> for($i = 0; $i < count($names); $i++)
> {
> eval('$name'.($i+1).' = "'.$names[$i].'";');
> }
>[/color]

You don't need eval for this:

for ($i = 0; $i < count($names); $i++) {
${'name'.($i+1)} = $names[$i];
}


JW



Trevor
Guest
 
Posts: n/a
#6: Jul 17 '05

re: PHP String Thing


Thank you very much, that's what I needed.

Trevor

Closed Thread