Having a problem returning an array from a function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tnspc
    New Member
    • Feb 2007
    • 30

    Having a problem returning an array from a function

    I'm writing code for a class where I've set up functions to load data from a file in the same directory as the PHP file (using the "file" method). Then, the goal is for the program to take the info from that function and, 1) search for a match from user-inputted names, 2) replace the old name (scanned by the second function) with the new name, and 3) save it back to the original file. The file contains info that was input to it by another PHP page, but that really doesn't matter. The problem is that I wrote the following test code to retrieve the info from the file, but it's not working properly.

    <?php
    function loadData()
    {
    if(!$filename = file("employees .dat"))
    {
    echo('Error while opening file');
    }
    else
    {

    $numLines = count($filename );
    for ($i = 0; $i < $numLines; $i++)
    {
    $filename[$i];
    }
    return array($filename );
    }
    }

    $myFile = loadData();
    echo($myFile);
    ?>

    Again, this is just a test code. The ultimate aim is not to print the array to the screen, but to retrieve the data from the function so that it can be passed on to the next function that will scan the array to see if an input from the user matches an existing name in the file. I can post the rest of the code after I get this part working correctly.

    P.S. The result of the function as it stands right now, is the word "Array" printed at the top left of the screen and nothing else. [It appears that it's returning the return TYPE instead of the actual values of the elements in the array]. Any help would be much appreciated, as all the other posts about similar issues seemed to be about databases, and not applicable. Thanks.
  • xwero
    New Member
    • Feb 2007
    • 99

    #2
    Originally posted by tnspc
    I'm writing code for a class where I've set up functions to load data from a file in the same directory as the PHP file (using the "file" method). Then, the goal is for the program to take the info from that function and, 1) search for a match from user-inputted names, 2) replace the old name (scanned by the second function) with the new name, and 3) save it back to the original file. The file contains info that was input to it by another PHP page, but that really doesn't matter. The problem is that I wrote the following test code to retrieve the info from the file, but it's not working properly.

    <?php
    function loadData()
    {
    if(!$filename = file("employees .dat"))
    {
    echo('Error while opening file');
    }
    else
    {

    $numLines = count($filename );
    for ($i = 0; $i < $numLines; $i++)
    {
    $filename[$i];
    }
    return array($filename );
    }
    }

    $myFile = loadData();
    echo($myFile);
    ?>

    Again, this is just a test code. The ultimate aim is not to print the array to the screen, but to retrieve the data from the function so that it can be passed on to the next function that will scan the array to see if an input from the user matches an existing name in the file. I can post the rest of the code after I get this part working correctly.

    P.S. The result of the function as it stands right now, is the word "Array" printed at the top left of the screen and nothing else. [It appears that it's returning the return TYPE instead of the actual values of the elements in the array]. Any help would be much appreciated, as all the other posts about similar issues seemed to be about databases, and not applicable. Thanks.
    to print an array to the screen you have to use print_r instead of echo.

    Your code looks fine.

    Comment

    • Motoma
      Recognized Expert Specialist
      • Jan 2007
      • 3236

      #3
      Originally posted by tnspc
      I'm writing code for a class where I've set up functions to load data from a file in the same directory as the PHP file (using the "file" method). Then, the goal is for the program to take the info from that function and, 1) search for a match from user-inputted names, 2) replace the old name (scanned by the second function) with the new name, and 3) save it back to the original file. The file contains info that was input to it by another PHP page, but that really doesn't matter. The problem is that I wrote the following test code to retrieve the info from the file, but it's not working properly.

      <?php
      function loadData()
      {
      if(!$filename = file("employees .dat"))
      {
      echo('Error while opening file');
      }
      else
      {

      $numLines = count($filename );
      for ($i = 0; $i < $numLines; $i++)
      {
      $filename[$i];
      }
      return array($filename );
      }
      }

      $myFile = loadData();
      echo($myFile);
      ?>

      Again, this is just a test code. The ultimate aim is not to print the array to the screen, but to retrieve the data from the function so that it can be passed on to the next function that will scan the array to see if an input from the user matches an existing name in the file. I can post the rest of the code after I get this part working correctly.

      P.S. The result of the function as it stands right now, is the word "Array" printed at the top left of the screen and nothing else. [It appears that it's returning the return TYPE instead of the actual values of the elements in the array]. Any help would be much appreciated, as all the other posts about similar issues seemed to be about databases, and not applicable. Thanks.

      To get the program to echo the actual data, the command you will need is print_r()

      Comment

      • tnspc
        New Member
        • Feb 2007
        • 30

        #4
        Thanks for your input. So, the last line would be print_r($myFile );?

        Comment

        • Motoma
          Recognized Expert Specialist
          • Jan 2007
          • 3236

          #5
          Originally posted by tnspc
          Thanks for your input. So, the last line would be print_r($myFile );?
          Yup. Try it and post your results if you have problems.

          Comment

          • tnspc
            New Member
            • Feb 2007
            • 30

            #6
            Thanks for your advice! It did display, although the main reason I had it display was to make the sure the array was being passed from the function to the main code. Now, on to problem #2! :o)

            The second function in this program takes the $myFile array passed from the previous function and loops through the elements to look for a match from the user-input form. The variable from the form is $oldName. Inside the function, I declare the local versions of those two variables (see comments on function). The professor wants us to return either the index of the array element that contains the match or -1 if no match is found. I have a loop that checks the array, but so far, it's not working. If I put a return outside the loop of -1, then nothing is found, and if I put it in the else clause, it only checks the first element of the array. Here's the code [note: I took the return -1 out already because I knew it wasn't working]:

            function searchData($myF ile, $oldName)
            {
            $a = $myFile;
            $s = $oldName;

            $numElements = count($a);
            for($i = 0; $i < $numElements; $i++)
            {
            if(eregi($oldNa me, $myFile))
            {
            return $i;
            }
            else
            $i++;
            }
            }


            It's called by the following line in the main body of the code:
            $index = searchData($myF ile, $oldName);

            *The reason we need to do it as an index or -1 is because that return value is used in the next if statement in the body that sets up the use of the last two functions to replace oldName with newName, and to write the data back to the original file accessed in the first function. I've tried a do-while loop as an alternative, but it didn't work either. Any suggestions?

            Comment

            • Motoma
              Recognized Expert Specialist
              • Jan 2007
              • 3236

              #7
              How about this:

              [php]
              function searchData($myF ile, $oldName)
              {
              $a = $myFile;
              $s = $oldName;

              $numElements = count($a);
              for($i = 0; $i < $numElements; $i++)
              if(eregi($oldNa me, $myFile)) return $i;
              return -1;
              }
              [/php]

              Comment

              • tnspc
                New Member
                • Feb 2007
                • 30

                #8
                Didn't work. Always returns -1, even if there's a match.

                Comment

                • Motoma
                  Recognized Expert Specialist
                  • Jan 2007
                  • 3236

                  #9
                  My Bad:

                  [php]
                  function searchData($myF ile, $oldName)
                  {
                  $numElements = count($myFile);
                  for($i = 0; $i < $numElements; $i++)
                  if(eregi($oldNa me, $myFile[$i])) return $i;
                  return -1;
                  }
                  [/php]

                  You forgot to put the index in $myFile that you wanted to compare to.

                  Comment

                  • tnspc
                    New Member
                    • Feb 2007
                    • 30

                    #10
                    Yeah, I noticed that and changed it, and it still did not work... it will return -1 unless the match is found with the first element (I believe). That's the problem I ran into that I haven't been able to solve yet. It needs to break out of the loop and return the index of the matching element if it finds it, or return -1 after the loop if no match. It may just be a problem with the placement of the return -1 statement; but, in another version of the code, I put it outside the loop brackets, and it was executing that statement every time, instead of returning from the function in the event of a match. For example:

                    function searchData($myF ile, $oldName)
                    {
                    $a = $myFile;
                    $s = $oldName;
                    {
                    $numElements = count($a);
                    for($i = 0; $i < $numElements; $i++)
                    {
                    if(!(eregi($s, $a[$i])))
                    {
                    return $i;
                    }
                    else
                    {
                    $i++;
                    }
                    }
                    }

                    return -1;
                    }

                    Comment

                    • tnspc
                      New Member
                      • Feb 2007
                      • 30

                      #11
                      I've got everything else working. The solution to the earlier problem was so simple, I wanted to shoot myself! I simply used a nested if statement, like so:

                      [PHP]function searchData($myF ile, $oldName)
                      {
                      $a = $myFile;
                      $s = $oldName;
                      {
                      $numElements = count($a);
                      for($i = 0; $i < $numElements; $i++)
                      {
                      if(!(eregi($s, $a[$i])))
                      {
                      return $i;
                      }
                      else
                      {
                      $i++;
                      }
                      }
                      }

                      return -1;
                      }[/PHP]


                      One last problem with the program...

                      How do I write the elements of the array BACK to the employees.dat file created earlier? I've tried a foreach loop, a listeach loop, and the simplest version, listed next:

                      [PHP]function saveData($myFil e)
                      {
                      echo("<br>"); //for testing purposes, to make sure that what's being passed
                      print_r($myFile ); //to the function is actually the info I want
                      echo("<br>");

                      if($file = fopen("employee s.dat", "w")):
                      $numElements = count($myFile);
                      for($i = 0; $i < $numElements; $i++)
                      {
                      fwrite($file, $myFile[$i]);
                      }
                      fclose($file);

                      else:
                      echo("Error in opening file. Please re-submit");
                      echo("<A HREF ='gradedLab3.ht m'>Return to form</A>");

                      endif;
                      }[/PHP]

                      All of these display the same thing when I browse to the file to check the results: inside the file is the word "Array" and nothing else. Please help so that I can finish this darn thing!! :o)

                      Comment

                      • tnspc
                        New Member
                        • Feb 2007
                        • 30

                        #12
                        Actually the solution to the first problem I noted above was actually:

                        [PHP]function searchData($myF ile, $oldName)
                        {
                        $a = $myFile;
                        $s = $oldName;

                        $numElements = count($myFile);
                        for($i = 0; $i < $numElements; $i++)
                        {
                        if((eregi($s, $a[$i])))
                        {
                        return $i;
                        }
                        else
                        {
                        if($i == $numElements-1)
                        {
                        return -1;
                        }
                        else
                        {
                        $i++;
                        }
                        }
                        }

                        }[/PHP]

                        Sorry, I was copied an older version of my file! Anyway, still working on problem #2...

                        Comment

                        • Motoma
                          Recognized Expert Specialist
                          • Jan 2007
                          • 3236

                          #13
                          The code I posted did not work?

                          Comment

                          • tnspc
                            New Member
                            • Feb 2007
                            • 30

                            #14
                            No, sorry, it did not. It gave me the same result I'd been getting, if I recall correctly... namely, it never found a match (always returned -1).

                            Comment

                            • Motoma
                              Recognized Expert Specialist
                              • Jan 2007
                              • 3236

                              #15
                              Originally posted by tnspc
                              No, sorry, it did not. It gave me the same result I'd been getting, if I recall correctly... namely, it never found a match (always returned -1).
                              I'm sorry, but
                              [php]
                              $arr = array("toast", "eggs", "bacon");

                              echo searchData($arr , "gs");

                              function searchData($myF ile, $oldName)
                              {
                              $numElements = count($myFile);
                              for($i = 0; $i < $numElements; $i++)
                              if(eregi($oldNa me, $myFile[$i])) return $i;
                              return -1;
                              }
                              [/php]
                              Works correctly for me.

                              Perhaps your array is not numerically ordered? Or multi dimensional?

                              Comment

                              Working...