Using array in a function

hi everyone.

i want to use an array ( already created outside the function ) in a function .

here is the code

page1.php


<form action="page2.php" method="post">
Marks1 = <input type="text" name="marks1" />
Marks2 = <input type="text" name="marks2" />
<input type="submit">

page2.php


extract($_POST);

$answer=array("$marks1","$marks2");

function numcheck($val,$answer)
{
	if(is_numeric($val))
	{
        return $val;
         }
	else
	{
	$newanswer=serialize($answer);
	$encode=urlencode($newanswer);
	header('location:level1test?num=numerror&encode=$encode');
	}
}

$result=array_filter($answer,"numcheck");

i am getting this error :- Missing argument 2 for numcheck()

i tried to use array inside the function also like this

function numcheck($val,$answer)
{
	if(is_numeric($val))
	{
        return $val;
         }
	else
	{

$answer=array("$marks1","$marks2");

	$newanswer=serialize($answer);
	$encode=urlencode($newanswer);
	header('location:level1test?num=numerror&encode=$encode');
	}
}

But now the error is undefined varible marks1 and marks2

How to get the $answer array inside the function ??

Hi, welcome to the forums!

The problem you’re having is because array_filter only passes one argument (an array element) to the function that you use with it.

Will there always be just two values returned from the form (i.e. marks1 and marks2), or that’s just an example and the actual form will have more?

Hi , thanks for reply ,
There are 30 values returned from the form …

i just want to use the $answer array inside the function numcheck

Why not just loop over the array with foreach? I’m not sure why you’re using extract to get the values from $_POST and then putting them back into an array?

If you named your input elements as an array, it would be easy to retrieve just the answers in your script:


<input type="text" name="answer[mark1]">
<input type="text" name="answer[mark2]">
<input type="text" name="answer[mark3]">


$answers = $_POST['answers'];

$results = array();
foreach ($answers as $question => $value)
{
    // process results
}

Also, I’m confused about what you’re trying to do here:


$newanswer = serialize($answer);
$encode = urlencode($newanswer);
header('location:level1test?num=numerror&encode=$encode');

Are you wanting to send back the names of the invalid inputs?

yes i am sending back the names…for invalid input… so serializing it before sending it through url… and your answer regarding declare array in name itself… is also interesting