Having a problem returning an array from a function

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

    #16
    Well, it's an array created by the file() method... perhaps it's an associative array?

    Comment

    • Motoma
      Recognized Expert Specialist
      • Jan 2007
      • 3236

      #17
      Originally posted by tnspc
      Well, it's an array created by the file() method... perhaps it's an associative array?
      In that case you would need to use a foreach() and return key() when found.

      But I don't know what your data looks like. Perhaps you could post it and I will be much more helpful.

      Comment

      • tnspc
        New Member
        • Feb 2007
        • 30

        #18
        Here's the entire code:

        ?php
        /*
        loadData: returns an array of lines in a file
        Parameters: the name of the file to be loaded, a string
        the default is "employees. dat"
        Returns: the array of lines in that file
        */

        //write loadData here
        function loadData($defau ltFileName = "employees.dat" )
        {
        if(!$defaultFil eName = file("employees .dat"))
        {
        echo('Error while opening file');
        }

        return $defaultFileNam e;
        }



        /*
        searchData: searches an array for a string
        Parameters: $myFile - the array to look through
        $oldName - the string to look for
        Returns: the index where the string is found in the array or -1 if not found
        */

        //write searchData here
        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++;
        }
        }
        }

        }


        /*
        updateData: updates lines in an array
        Parameters: $a - the array
        $i - index in the array to update
        $sOld - name in string to replace
        $sNew - name to replace $sOld with
        */

        //write updateData here
        function updateData($myF ile, $index, $oldName, $newName)
        {
        $a = $myFile;
        $i = $index;
        $sOld = $oldName;
        $sNew = $newName;

        $a[$i] = eregi_replace($ sOld,$sNew, $a[$i]);
        return array($a);

        }



        /*
        saveData: saves array to a file, does not save empty array elements
        Parameters: $a - array to be saved
        $defaultFilenam e - name of file, default value "employees. dat"
        */
        //write saveData here
        function saveData($myFil e)
        {
        echo("<br>");
        print_r($myFile );
        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;
        }






        if(!empty($newN ame)):
        $myFile = loadData();
        $index = searchData($myF ile,$oldName);
        if($index == -1):
        echo("<HTML><HE AD><TITLE>$name not found</TITLE></HEAD><BODY>");
        echo("<B>$name</B> not found <BR>");
        echo("<A HREF ='gradedLab3.ht m'>Return to form</A>");
        echo("<B>$name</B></HTML>");
        exit();
        else:
        //update name and save data
        //call updateData here

        $myFile = updateData($myF ile, $index, $oldName, $newName);
        saveData($myFil e);

        ?>

        <HTML>
        <HEAD>
        <TITLE>Employ ee Updated</TITLE>
        </HEAD>
        <BODY>
        <B><?php echo($oldName); ?></B> was updated <?php echo("to $newName"); ?><BR>
        <A HREF = "gradedLab3.htm ">Return to Form</A>

        </BODY>
        </HTML>
        <?php
        endif;
        else:

        ?>

        <HTML>
        <HEAD>
        <TITLE>No Name</TITLE>
        </HEAD>
        <BODY>
        <B>No name was submitted</B><BR>
        <A HREF = "gradedLab3.htm ">Return to Form</A>

        </BODY>
        </HTML>

        <?php

        endif;
        ?>


        The original Employees.dat file looks like this:

        Personnel Attila T Hun 888.333.4444 5086
        Personnel Dirk Diggler 888.333.4444 928
        Personnel Donkey Kong 888.222.5555 8989

        (It is created and added to by a previous PHP/HTML script)

        The idea of this code is to replace an $oldName in the file with a $newName, both input by the user through a form referenced in the code above. For example, after writing back to the employees.dat file, the finished product should look like:

        Personnel Attila T Hun 888.333.4444 5086
        Personnel Dirk Diggler 888.333.4444 928
        Personnel P Diddy Kong 888.222.5555 8989


        Does that all make sense now? :o)

        Comment

        • ronverdonk
          Recognized Expert Specialist
          • Jul 2006
          • 4259

          #19
          No it does not! It is an absolute mess to read your code!

          Before you show any code, read the Posting Guidelines at the top of this forum. Especially the part about enclosing shown code within php or code tags!!

          moderator

          Comment

          • Motoma
            Recognized Expert Specialist
            • Jan 2007
            • 3236

            #20
            First: use [PHP ] [/PHP ] around your code when you post. This will give me, the person who is trying to help you, color coding.

            Second: Post the results of print_r() on your array.

            Comment

            • tnspc
              New Member
              • Feb 2007
              • 30

              #21
              [PHP]?php
              /*
              loadData: returns an array of lines in a file
              Parameters: the name of the file to be loaded, a string
              the default is "employees. dat"
              Returns: the array of lines in that file
              */

              //write loadData here
              function loadData($defau ltFileName = "employees.dat" )
              {
              if(!$defaultFil eName = file("employees .dat"))
              {
              echo('Error while opening file');
              }

              return $defaultFileNam e;
              }



              /*
              searchData: searches an array for a string
              Parameters: $myFile - the array to look through
              $oldName - the string to look for
              Returns: the index where the string is found in the array or -1 if not found
              */

              //write searchData here
              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++;
              }
              }
              }

              }


              /*
              updateData: updates lines in an array
              Parameters: $a - the array
              $i - index in the array to update
              $sOld - name in string to replace
              $sNew - name to replace $sOld with
              */

              //write updateData here
              function updateData($myF ile, $index, $oldName, $newName)
              {
              $a = $myFile;
              $i = $index;
              $sOld = $oldName;
              $sNew = $newName;

              $a[$i] = eregi_replace($ sOld,$sNew, $a[$i]);
              return array($a);

              }



              /*
              saveData: saves array to a file, does not save empty array elements
              Parameters: $a - array to be saved
              $defaultFilenam e - name of file, default value "employees. dat"
              */
              //write saveData here
              function saveData($myFil e)
              {
              echo("<br>");
              print_r($myFile );
              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;
              }






              if(!empty($newN ame)):
              $myFile = loadData();
              $index = searchData($myF ile,$oldName);
              if($index == -1):
              echo("<HTML><HE AD><TITLE>$name not found</TITLE></HEAD><BODY>");
              echo("<B>$name</B> not found <BR>");
              echo("<A HREF ='gradedLab3.ht m'>Return to form</A>");
              echo("<B>$name</B></HTML>");
              exit();
              else:
              //update name and save data
              //call updateData here

              $myFile = updateData($myF ile, $index, $oldName, $newName);
              saveData($myFil e);

              ?>[/PHP]
              [HTML]<HTML>
              <HEAD>
              <TITLE>Employ ee Updated</TITLE>
              </HEAD>
              <BODY>
              <B><?php echo($oldName); ?></B> was updated <?php echo("to $newName"); ?><BR>
              <A HREF = "gradedLab3.htm ">Return to Form</A>

              </BODY>
              </HTML>
              <?php
              endif;
              else:

              ?>

              <HTML>
              <HEAD>
              <TITLE>No Name</TITLE>
              </HEAD>
              <BODY>
              <B>No name was submitted</B><BR>
              <A HREF = "gradedLab3.htm ">Return to Form</A>

              </BODY>
              </HTML>

              <?php

              endif;
              ?>



              [/HTML]

              Comment

              • tnspc
                New Member
                • Feb 2007
                • 30

                #22
                That's the full code, other than the original PHP script that creates the file "employees.dat" . That should make it clearer.

                Comment

                • Motoma
                  Recognized Expert Specialist
                  • Jan 2007
                  • 3236

                  #23
                  Originally posted by tnspc
                  That's the full code, other than the original PHP script that creates the file "employees.dat" . That should make it clearer.

                  What are the results of the print_r()?
                  The key to understanding how to parse your data is knowing what your data is.

                  Comment

                  • tnspc
                    New Member
                    • Feb 2007
                    • 30

                    #24
                    The results are exactly what I expected. Before the attempt at writing to the file, I get the elements of the array as:

                    Array ( [0] => Array ( [0] => Personnel Billy Bob Thornton 888.333.4444 5086 [1] => Personnel Bozo Clown 888.333.4444 928 [2] => Personnel Donkey Kong 888.222.5555 8989 ) )

                    But, the result after trying the fwrite, is simply the word "Array" being written to the file. What do you think?

                    Comment

                    • Motoma
                      Recognized Expert Specialist
                      • Jan 2007
                      • 3236

                      #25
                      Originally posted by tnspc
                      The results are exactly what I expected. Before the attempt at writing to the file, I get the elements of the array as:

                      Array ( [0] => Array ( [0] => Personnel Billy Bob Thornton 888.333.4444 5086 [1] => Personnel Bozo Clown 888.333.4444 928 [2] => Personnel Donkey Kong 888.222.5555 8989 ) )

                      But, the result after trying the fwrite, is simply the word "Array" being written to the file. What do you think?
                      You have a multi dimensional array.
                      Your first element in your first array is an array. You will need another layer of indexing to get to the second one:
                      [php]
                      echo $myFile[0][1]; // will give you "Personell Boso Clown 888.222.444 928"
                      [/php]

                      Comment

                      • tnspc
                        New Member
                        • Feb 2007
                        • 30

                        #26
                        Your questions have been extremely helpful! I actually realized, after showing you the output on my last post, that this IS an associative array. I had been seeing one thing in my mind instead of using my eyes to process what was actually happening. Now, my last dilemna is how to get all the lines to write back to the file, as the fwrite command deletes everything in the file to write the new info in... so I can't use a for loop with fwrite command in it, or I only get the first line. Any suggestions?

                        Comment

                        • Motoma
                          Recognized Expert Specialist
                          • Jan 2007
                          • 3236

                          #27
                          Originally posted by tnspc
                          Your questions have been extremely helpful! I actually realized, after showing you the output on my last post, that this IS an associative array. I had been seeing one thing in my mind instead of using my eyes to process what was actually happening. Now, my last dilemna is how to get all the lines to write back to the file, as the fwrite command deletes everything in the file to write the new info in... so I can't use a for loop with fwrite command in it, or I only get the first line. Any suggestions?
                          A: Concatenate the data first, then write with one call.
                          B: Use the var_export function I showed you to in your other thread.

                          Comment

                          • tnspc
                            New Member
                            • Feb 2007
                            • 30

                            #28
                            Originally posted by Motoma
                            A: Concatenate the data first, then write with one call.
                            B: Use the var_export function I showed you to in your other thread.

                            I'm trying to concatenate with the following code:

                            [PHP] $a = "";
                            $numElements = count($myFile);
                            for($i = 0; $i < $numElements; i++)
                            {
                            $a .= $myFile[0][$i];
                            }[/PHP]

                            for some reason, it's only giving me the first element of the array (i.e. the first employee's info). Any ideas?

                            P.S. Var_export is no good, because I don't want the array printed to the screen. I only have it displaying earlier as a check of my code.

                            Comment

                            • tnspc
                              New Member
                              • Feb 2007
                              • 30

                              #29
                              SUCCESS!!! My textbook was finally good for something besides a paperweight... the solution is:


                              [PHP] while(list($ind ex) = each($myFile))
                              {
                              for($i = 0; $i < count($myFile[$index]); $i++);
                              {
                              $a .= $myFile[$index][$i];
                              }
                              }
                              fwrite($file, $a);
                              fclose($file);
                              [/PHP]

                              Comment

                              • Motoma
                                Recognized Expert Specialist
                                • Jan 2007
                                • 3236

                                #30
                                Glad to see you got things figured out. It's too bad that you had to go through days of confusion with me when the answer was right there all along.
                                But if my ramblings enticed you to pick up your text book and learn PHP, I guess I can feel good about myself.

                                Comment

                                Working...