Help with Array and File

Hi all,

Very new to PHP and ran into some trouble and was wondering if anyone could help. I’m having problems with an array of names that are looked up in a database. When I use just the array of names it gets processed correctly. When I try and read a file of those same names only the last name gets displayed. Please see examples and code below. Thanks for your time.

//This works – Sample 1
$x=array(“joe”, “paul”, “tom”);

//This does not – Sample 2
$x = file(“names.txt”); //Same names from the array above are in this file

Here is the full code below.

Name Check <?php $con = mysql_connect("localhost","xxxxxxxx","xxxxxxxx"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("xxxxxxxxxx", $con); //$x=array("joe", "paul", "tom"); //displays all names correctly in Sample 1 below //$x = file("name.txt"); //only displays the last name in the file. Sample 2 below foreach ($x as $test) { $result = mysql_query("SELECT * FROM categories WHERE Name='$test' Limit 0, 1"); while($row = mysql_fetch_array($result)) { echo $row['Name']; echo " " . $row['Sport']; echo "
"; } } ?>

Sample 1 output

joe basketball
paul basketball
tom baseball

Sample 2 output

tom baseball

Hi john ;D

The below example assumes the names in the text file are separated by one tabspace (you can change this to whatever you use, i just chose it for this example)

$x = file(“name.txt”); // read the contents of the name.txt file (each name separated by a tab “\t”)
$y = explode("\t", $x[0]); // explode the string into and array using the tab as a marker to separate)

foreach ($y as $test) etc etc…

this should do what you need :wink:

Sponsor our Newsletter | Privacy Policy | Terms of Service