I am trying to get first name and last name from a text file with while loop and store it in a global variable to which i want to access from any other function to echo all the first and last name in two different keys.
Here is my full code.
<?php
OutputNames();
function ReadNames()
{
$myFile = new SplFileObject("all/names.txt");
while (!$myFile->eof()) {
$row = str_getcsv($myFile->fgets());
$first = $row[0];
$last = $row[1];
}
}
function OutputNames()
{
echo $first." ".$last;
}
?>
Your code (or at least the part you've shown) really makes very little sense.
You're not actually using any global variables at all, so the $first and $last variables in each function are only in scope within those functions.
You never call ReadNames() anywhere, so it's not clear if it's ever being executed at all.
ReadNames() never returns any values, so the $first and $last variables simply cease to exist when the function ends.
The while loop in Readnames overwrites the $last variable every time it loops, instead of appending to it. But even then it wouldn't make sense because you'd end up with a list of first names and a list of last names, with no link between the first/last names which originally belonged together. A multidimensional associative array would make more sense to store the data (prior to displaying it).
Globals are generally a poor way to transfer information around your application - it's easy to get confused, have scoping issues, have things get overwritten, or cause conflicts between different parts of the code. Returning values from functions, and/or encapsulating functionality and data structures within objects are more reliable, testable and maintainable approaches.
It's not clear what actual flow you wanted / intended, but maybe something like this makes more sense?
OutputNames();
function ReadNames()
{
$myFile = new SplFileObject("all/names.txt");
$data = array();
while (!$myFile->eof()) {
$row = str_getcsv($myFile->fgets());
$data[] = array ("first" => $row[0], "last" => $row[1]);
}
return $data;
}
function OutputNames()
{
$results = ReadNames();
foreach ($results as $result) {
echo $result["first"]." ".$result["last"]."<br/>";
}
}
It depends at what point in the process you actually want to do the reading from the CSV file, and whether you want to do it once and then re-use the results repeatedly, or what. If the code above doesn't resolve the issue fully, you'll need to clarify the exact requirements.