I have this code and no code before it that refers to any variables seen below. Yet I still can't find why I'm getting the error: "First argument should be an array in..."
$array = array("element here for reason");
function sortdata()
{
$File = fopen("Names.txt", "r");
//put each file line into an array element
while(!feof($File))
{
array_push($array, fgets($File));
}
}
$array
is out of scope to the function. You can bring it into scope using global
.
$array = ..;
function sortdata() {
global $array;
...
}
sortdata();
Alternatively, you can pass it by reference into the function.
$array = ..;
function sortdata(&$array) {
...
}
sortdata($array);
You should try to first initialize the array and bring the array within the scope of the function like so:
$array = array();
array_push($array, "element here for reason");
function sortdata()
{
global $array;
$File = fopen("Names.txt", "r");
//put each file line into an array element
while(!feof($File))
{
array_push($array, fgets($File));
}
}
The issue with the code is that you are not passing the $array variable into the function. Aside from that, it would be more efficient to use the shortcut way to add an item to the array instead of calling array_push since it eliminates the overhead of calling a function.
$array = array("element here for reason");
function sortdata($array)
{
$File = fopen("Names.txt", "r");
//put each file line into an array element
while(!feof($File))
{
$array[] = fgets($File);
}
return $array;
}
You use variable $array inside function body. In this case this is local variable and it automatically sets to string.
For work with your global variable $array you should use instruction global in your function.
function sortdata() {
global $array;
/* there your code for work with $array */
}
This give you backward compatibility
function sortdata(array $array = array())
{
$File = fopen("Names.txt", "r");
while(!feof($File))
{
array_push($array, fgets($File));
}
return $array;
}