0
function acids(){
    $acidsarray=array('lemonjuice','vinegar','sherry','champagne','orange');
    $acids=array_rand($acidsarray);
    echo $acids;
}

Hello, I'm new to programming and this is a function I've written, the idea is it's supposed to spit out one of the ingredients from the array; when I run it it returns a number, usually between 0 and 4, so it's doing something though not what I want it to do. Can you see where I'm going wrong?

I've written the function in python, using the same logic and it works fine.

Thank you

1

4 Answers 4

3

array_rand returns the key only, so when you echo you'd need to instead echo:

echo $acidsarray[$acids];
Sign up to request clarification or add additional context in comments.

2 Comments

Right, so in Php lingo i need to go a step further and hook the random picker to the actual array.
Yeah, basically it returns an identifier rather than the data
0

You want to do the following:

function acids(){
            $acidsarray=array('lemonjuice','vinegar','sherry','champagne','orange');
            $acids=$acidsarray[array_rand($acidsarray)];
            echo $acids;
}

Because the docs say

Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.

Comments

0

If you'd read the documentation, you'd have seen array_rand returns a random index valid for subsequently using on the array.

So you'll need to add:

$acids = $acidsarray[$acids];

Comments

0

You can also use shuffle function to serve random value.

function acids(){
    $acidsarray = array('lemonjuice','vinegar','sherry','champagne','orange');
    shuffle($acidsarray);
    echo $acidsarray[0];
}

1 Comment

might come in handy someday :)

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.