PDA

View Full Version : Functions and Arrays


briintex1
09-20-2004, 03:04 AM
I am tryin' to figure out if I am doing functions right or not. I was wondering if I could return an array, I know if other lang. like C++ and vb you can return an array but this is primarly setting a variable as the number inside the array.
I know right now I have an error on line #2 the error reads
Parse error: parse error, unexpected '[', expecting ')' in /home/cypressp/public_html/test.php on line 2
<?
function random_quotes($quotes[random_number])
//the following sets ththe array for the quotes
$quotes[] = 'First quote';
$quotes[] = 'Second quote';
$quotes[] = 'Third quote';
//the following sets the random number to be put in the array so the quote will be choosen
srand ((double) microtime() * 1000000);
$random_number = rand(0,count($quotes)-1);
return $quotes[$random_number];
?>

<html>
<title>CodeAve.com (JavaScript: Textbox Change OnClick)</title>
<body bgcolor="#FFFFFF">
<?
random_quotes($quotes[$random_number]; //this line should call the function
$that2 = $quotes[$random_number]; //I set this here so I can call the function and set it to a variable
random_quotes($quotes[$random_number]; //this line should call the function
$that1 = $quotes[$random_number]; //I set this here so I can call the function and set it to a variable that way it will be different than the one aboveecho($that2);
echo($that1);
?>

</body>
</html>

Thanks in advance for the help

AaronW
09-20-2004, 03:16 AM
Well I'm dead tired, but saw your post and figured I'd post what I noticed off the bat:

The function syntax is as follows:

function <funcName> (<argument1>, <argument2>, ...)
{
// Procedure code here
}

So in your case, you'd probably want:

function getRandomValue ($array)
{
return $array[rand (0, count ($array) - 1)];
}

That function will return a random value from the array you pass it:


// Echo a random animal name from the array we pass it
echo getRandomValue (array ('cow', 'pig', 'chicken', 'horse'));


My code's untested, but it should work... Heh. G'night and g'luck.

trib4lmaniac
09-20-2004, 01:01 PM
Just use

function get_rand($array) {
return $array( array_rand($array) );
}

That doesn't require numerical keys either.

AaronW
09-20-2004, 03:22 PM
Heh. array_rand didn't come to mind... Yeah that's much easier, and works for associative arrays too.