Jump to content


Photo

explode() help needed


  • Please log in to reply
4 replies to this topic

#1 marcus

marcus
  • Members
  • PipPipPip
  • Advanced Member
  • 1,842 posts
  • LocationRochester, NY

Posted 29 October 2006 - 09:04 PM

Ok, I'm having trouble exploding text from my file facts.txt

<?
$r = rand(1,1);
$f = explode("*",facts.txt);
echo $f[$r];
?>

what am i doing wrong?

#2 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 29 October 2006 - 09:12 PM

You have to read the file first. What are you trying to do?

Ken

#3 marcus

marcus
  • Members
  • PipPipPip
  • Advanced Member
  • 1,842 posts
  • LocationRochester, NY

Posted 30 October 2006 - 10:36 PM

I am trying to explode text from the file.

Would I have to do

<?
$file = fopen("facts.txt","r");
$f = explode("*",$file);
$r = rand(1,1);
echo $f[$r];
?>


#4 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 30 October 2006 - 10:51 PM

Explode() takes a string as it's second parameter. In your script, the variable $file is a file handle not a string. From the description of what you want to do, it looks like you file contains works seperated by the "*" character and you want to select one at random.

Try this:
<?php
$fc = file_get_contents('facts.txt'); //read the contents of the file into a string
$fc_array = explode('*',$fc); // create the array
echo $fc_array[array_rand($fc_array)]; // use the function array_rand() to get a random index in the $fc_array array.
?>

Ken

#5 marcus

marcus
  • Members
  • PipPipPip
  • Advanced Member
  • 1,842 posts
  • LocationRochester, NY

Posted 30 October 2006 - 10:54 PM

Thanks Ken, works beautifully!




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users