Can someone tell me what the syntax for doing a function to an array or is that not possible?
Can you explain the code you gave? 'Cause I’m a beginner and I don’t know all the premade stuff.
I’m trying to make a poll so I have a function that goes through the database (or at least it’s supposed to, It’s not finished so I can’t see if it works) and counts how many of a certain option and puts it in a variable. But since obviously there’s going to be multiple options there has to be multiple variables to hold the different numbers in. I might want a lot of options in my poll so I decided to make this into an array. I learned in a different programming language (which I’m not sure if it’s the same here or not) that the purpose of a function is for it to give you a number in a variable or return a value. Since I’m going to have multiple poll options, there would need to be just as variables to hold the outcome of how many votes in each option, so I thought that would mean that I would need multiple functions. Then I decided I should have a for loop so that it can do the function with each variable from the array so at the end each option of the poll can have a variable with a number of how many votes it has.
This may accomplish what you are looking for:
function get_poll_results($data) {
//query your database
//this is just a quick example, be sure to sanitize your data
$result = mysql_query("SELECT count(*) AS this_poll FROM yourtable WHERE votes='$data");
$r = mysql_fetch_assoc($result);
return $r['this_poll'];
}
$votesArray = array('option1', 'option2', 'option3');
foreach ($votesArray as $value) {
echo $value.': '.get_poll_results($value).'<br/>';
}
//or if you want the final result in an array do this
$finalarray = array();
foreach ($votesArray as $value) {
$finalarray[$value] = get_poll_results($value);
}
I don’t think that’s quite what I’m trying to do. Would that give you a bunch of poll results? The way I thought it was going to work was I do this function and for example, the first time when the name of the first variable in the array is $option1 the function computes how many votes there are for a certain poll option and puts the number in $option1 and returns the value. It would then go on to do that for everything else in the array for example $option2 until you get to $option20 (or however many options I want in my poll.
Would that work for that?
If I’m understanding you correctly, yes, you can return an array from a function.
See Example #2 at http://nz.php.net/manual/en/functions.returning-values.php
At first glance it’s not possible, but perhaps with more information about what wants to be done and why, a solution might be able to be crafted for you.