Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
How to define while loop result in a global variable and use it in another function to process another task

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;
}

?>
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Your code (or at least the part you've shown) really makes very little sense.

  1. 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.

  2. You never call ReadNames() anywhere, so it's not clear if it's ever being executed at all.

  3. ReadNames() never returns any values, so the $first and $last variables simply cease to exist when the function ends.

  4. 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).

  5. 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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda