Forum Moderators: coopster

Message Too Old, No Replies

How do I turn strings into arrays?

can I do it?

         

electricocean

7:58 pm on May 24, 2005 (gmt 0)

10+ Year Member



How do I turn a string into array where all the characters in the string to seprate values.

Something like this:

$string = "High";

to this:

$array = array('h','i','g', 'h');

Thanks,
electricocean

Timotheos

8:53 pm on May 24, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



From the manual...

$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);

dreamcatcher

7:46 am on May 25, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



A string is already an array.

$string = "High";

echo $string[0];
echo $string[1];
echo $string[2];
echo $string[3];

or

for ($i=0; $i<strlen($string); $i++)
{
echo $string[$i];
}

or

$new = array();

for ($i=0; $i<strlen($string); $i++)
{
$new[] = $string[$i];
}

Hope that also helps.

dc

gliff

2:09 pm on May 25, 2005 (gmt 0)

10+ Year Member



Square brackets for accessing single string characters is depreciated [us3.php.net]. Use curly brackets instead.

print($string[0]); //will work now, may not in future

print($string{0}); //"better"

Timotheos

3:44 pm on May 25, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



That's cool! They must have changed to curly brackets because technically a string is not an array. That is, you can't use the array functions just on a string. So I like your second method dreamcatcher. I wonder which one would be faster?

Timotheos

8:08 pm on May 25, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I was looking for something else and found this.

$str = 'string';
$chars = str_split($str);
print_r($chars);

More then one way to skin a cat...

jatar_k

8:10 pm on May 25, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



watch that one Tim, PHP 5 only

wished I could use that function more than once ;)

ergophobe

9:12 pm on May 25, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




wished I could use that function more than once ;)

I felt the same way about file_put_contents(). It seemed so sad that file_get_contents() works in PHP4, but it's complement doesn't, so now I put a file_get_contents() in my standard library with a conditional function definition so it only gets defined if the function file_get_contents() doesn't exist.

Timotheos

11:36 pm on May 25, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



watch that one Tim, PHP 5 only

Hehe, sorry. Guess I'm getting lazy with this custom intranet app running 5 ;-)

electricocean

11:24 pm on May 31, 2005 (gmt 0)

10+ Year Member



I am just getting into for statements... do any of you know a good tut becuase I kinda confuzled.

thanks,
electricocean

Timotheos

12:43 am on Jun 1, 2005 (gmt 0)