473,503 Members | 11,735 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Having a problem returning an array from a function

30 New Member
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
29 2278
xwero
99 New Member
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
3,237 Recognized Expert Specialist
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
tnspc
30 New Member
Thanks for your input. So, the last line would be print_r($myFile);?
Feb 26 '07 #4
Motoma
3,237 Recognized Expert Specialist
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
tnspc
30 New Member
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
3,237 Recognized Expert Specialist
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
tnspc
30 New Member
Didn't work. Always returns -1, even if there's a match.
Feb 26 '07 #8
Motoma
3,237 Recognized Expert Specialist
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
tnspc
30 New Member
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
tnspc
30 New Member
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
tnspc
30 New Member
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
3,237 Recognized Expert Specialist
The code I posted did not work?
Feb 28 '07 #13
tnspc
30 New Member
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
3,237 Recognized Expert Specialist
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
tnspc
30 New Member
Well, it's an array created by the file() method... perhaps it's an associative array?
Feb 28 '07 #16
Motoma
3,237 Recognized Expert Specialist
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
tnspc
30 New Member
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
4,258 Recognized Expert Specialist
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
3,237 Recognized Expert Specialist
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
tnspc
30 New Member
[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
tnspc
30 New Member
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
3,237 Recognized Expert Specialist
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
tnspc
30 New Member
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
3,237 Recognized Expert Specialist
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
tnspc
30 New Member
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
3,237 Recognized Expert Specialist
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
tnspc
30 New Member
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
tnspc
30 New Member
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
3,237 Recognized Expert Specialist
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

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

Similar topics

6
14000
by: Krackers | last post by:
How do you write a function which returns a reference to an array. I can only get a function to return a copy of the array itself. I've had a look at some other threads in this group an the return...
7
7273
by: BrianJones | last post by:
Hi, if you have a function, how is it possible to return an array? E.g.: unsigned long function(...) // what I want to do, obviously illegal I do know such would be possible by using a dynamic...
12
2736
by: LongBow | last post by:
Hello all, From doing a google serach in the newsgroups I found out that a string can't be returned from a function, but using a char* I should be able to do it. I have spent most of the day...
41
3750
by: Materialised | last post by:
I am writing a simple function to initialise 3 variables to pesudo random numbers. I have a function which is as follows int randomise( int x, int y, intz) { srand((unsigned)time(NULL)); x...
3
1834
by: Carramba | last post by:
hi! the code is cinpiling with gcc -ansi -pedantic. so Iam back to my question Iam trying to make program were I enter string and serach char. and funktion prints out witch position char is...
13
4764
by: Jordan Tiona | last post by:
Is this not allowed in C++? I try in MSVC, but I always get an error, and the function no longer shows up in my class view.
17
3218
by: I.M. !Knuth | last post by:
Hi. I'm more-or-less a C newbie. I thought I had pointers under control until I started goofing around with this: ...
0
1028
by: ppuniversal | last post by:
hello, I am making an application where I have to copy the values of some of the tuples(which are not already copied into the files) from my database in MySQL into two files.Now I have an attribute...
0
7098
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7364
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7470
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5604
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5026
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4696
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3186
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1524
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
751
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.