0

I'm trying to create a page that will dynamically create input buttons if the string contains an "a" and otherwise increment the value and display the string. Here is my function that checks it, it works but every input has the same name, and $num does not get updated.

Any help would be much appreciated, thanks in advance.

$num = 0;

function isAnswer($a, $i) {
    if (strpos($a, 'a') !== false) {
        return '<input type="radio" name="gender'.$num.'" value="male">';
    } else {
        ++$num;
        return $a .":";
    }
}
1

1 Answer 1

1

Thats because $num is outside function scope.

Adding global $num within function. (quick solution)

Do this:

$num = 0;

function isAnswer($a, $i) {
   global $num;

    if (strpos($a, 'a') !== false) {
        return '<input type="radio" name="gender'.$num.'" value="male">';
    } else {
        ++$num;
        return $a .":";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.