By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,397 Members | 2,552 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,397 IT Pros & Developers. It's quick & easy.

Having a problem returning an array from a function

P: 30
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.
Feb 26 '07 #1
Share this Question
Share on Google+
29 Replies


P: 99
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.
Feb 26 '07 #2

Motoma
Expert 2.5K+
P: 3,235
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()
Feb 26 '07 #3

P: 30
Thanks for your input. So, the last line would be print_r($myFile);?
Feb 26 '07 #4

Motoma
Expert 2.5K+
P: 3,235
Thanks for your input. So, the last line would be print_r($myFile);?
Yup. Try it and post your results if you have problems.
Feb 26 '07 #5

P: 30
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($myFile, $oldName)
{
$a = $myFile;
$s = $oldName;

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


It's called by the following line in the main body of the code:
$index = searchData($myFile, $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?
Feb 26 '07 #6

Motoma
Expert 2.5K+
P: 3,235
How about this:

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

$numElements = count($a);
for($i = 0; $i < $numElements; $i++)
if(eregi($oldName, $myFile)) return $i;
return -1;
}
[/php]
Feb 26 '07 #7

P: 30
Didn't work. Always returns -1, even if there's a match.
Feb 26 '07 #8

Motoma
Expert 2.5K+
P: 3,235
My Bad:

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

You forgot to put the index in $myFile that you wanted to compare to.
Feb 26 '07 #9

P: 30
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($myFile, $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;
}
Feb 27 '07 #10

P: 30
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($myFile, $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($myFile)
{
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("employees.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.htm'>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)
Feb 28 '07 #11

P: 30
Actually the solution to the first problem I noted above was actually:

[PHP]function searchData($myFile, $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...
Feb 28 '07 #12

Motoma
Expert 2.5K+
P: 3,235
The code I posted did not work?
Feb 28 '07 #13

P: 30
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).
Feb 28 '07 #14

Motoma
Expert 2.5K+
P: 3,235
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($myFile, $oldName)
{
$numElements = count($myFile);
for($i = 0; $i < $numElements; $i++)
if(eregi($oldName, $myFile[$i])) return $i;
return -1;
}
[/php]
Works correctly for me.

Perhaps your array is not numerically ordered? Or multi dimensional?
Feb 28 '07 #15

P: 30
Well, it's an array created by the file() method... perhaps it's an associative array?
Feb 28 '07 #16

Motoma
Expert 2.5K+
P: 3,235
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.
Feb 28 '07 #17

P: 30
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($defaultFileName = "employees.dat")
{
if(!$defaultFileName = file("employees.dat"))
{
echo('Error while opening file');
}

return $defaultFileName;
}



/*
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($myFile, $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($myFile, $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
$defaultFilename - name of file, default value "employees.dat"
*/
//write saveData here
function saveData($myFile)
{
echo("<br>");
print_r($myFile);
echo("<br>");

if($file = fopen("employees.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.htm'>Return to form</A>");

endif;
}






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

$myFile = updateData($myFile, $index, $oldName, $newName);
saveData($myFile);

?>

<HTML>
<HEAD>
<TITLE>Employee 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)
Feb 28 '07 #18

ronverdonk
Expert 2.5K+
P: 4,258
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
Feb 28 '07 #19

Motoma
Expert 2.5K+
P: 3,235
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.
Feb 28 '07 #20

P: 30
[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($defaultFileName = "employees.dat")
{
if(!$defaultFileName = file("employees.dat"))
{
echo('Error while opening file');
}

return $defaultFileName;
}



/*
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($myFile, $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($myFile, $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
$defaultFilename - name of file, default value "employees.dat"
*/
//write saveData here
function saveData($myFile)
{
echo("<br>");
print_r($myFile);
echo("<br>");

if($file = fopen("employees.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.htm'>Return to form</A>");

endif;
}






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

$myFile = updateData($myFile, $index, $oldName, $newName);
saveData($myFile);

?>[/PHP]
[HTML]<HTML>
<HEAD>
<TITLE>Employee 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]
Feb 28 '07 #21

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

Motoma
Expert 2.5K+
P: 3,235
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.
Mar 1 '07 #23

P: 30
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?
Mar 1 '07 #24

Motoma
Expert 2.5K+
P: 3,235
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]
Mar 1 '07 #25

P: 30
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?
Mar 1 '07 #26

Motoma
Expert 2.5K+
P: 3,235
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.
Mar 1 '07 #27

P: 30
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.
Mar 1 '07 #28

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


[PHP] while(list($index) = each($myFile))
{
for($i = 0; $i < count($myFile[$index]); $i++);
{
$a .= $myFile[$index][$i];
}
}
fwrite($file, $a);
fclose($file);
[/PHP]
Mar 1 '07 #29

Motoma
Expert 2.5K+
P: 3,235
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.
Mar 1 '07 #30

Post your reply

Sign in to post your reply or Sign up for a free account.