Help with array

I’m trying an array for the first time, but it’s not working like I wanted. Can someone tell me what it is I’m doing wrong? I appreciate any help.

This is the first part of the code, an html file:


Name my pet

Want us to name your pet?

Enter a number between 0 and 25:


This is the second part:

$animals = array (“Phoebe” , “crack” , “socket” , “radish” , “shady” , “beaver”);

$animals = $_REQUEST[  "$animals[ ]" ] ;


You’re trying to fetch in the wrong way:

$animals = intval($_POST['animals']);

First of all, when you make bigger scripts, you will want to know just where exactly your data is coming from. In order to do so, I’ve replaced $_REQUEST with $_POST. Basically it has the same effect, except for that you’re excluding $_GET, $_COOKIE, $_SERVER, $_ENV and $_SESSION variables. Makes things a little neat and tidy.

Secondly, I’ve changed the name of the array index from ‘$animals[ ]’ to ‘animals’. This because in the form, your text input is also called ‘animals’, and not ‘$animals[ ]’.

Third, which is a security measure, I’ve used the function intval(). This function converts the value of $_POST[‘animals’] to an integer value. If the value is a string, object, or w/e, it tries to discern a number, if it can’t, it returns 0. This way, you won’t be stuck with unexpected values that may crash your script.

Also, use error_reporting(E_ALL) for debugging purposes. See also my signature ;)

Thanks for the reply. I tried changing it like you displayed, unfortunately, it still doesn’t work for me. Just getting a blank page. :cry:

Are you outputting your values anywhere, using echo or print?

The code is as you see it, no echo or print.

Then no output ;)

Silly me! I added the echo $_Post, however I still was getting a blank page. When I first saw this code, it has Request where the post was. So I changed it back to request. Now I get the number that I put in the text box. Not the name.

I’m wondering, does it matter where the array is? Should the array be in the namemypet.html page? Or should I leave it in the animals.php page? Is there something I’m missing? Should there be more code in either page to make it work? I’m pulling my hair out here!

You’re assigning the value that was put into the textbox in the form to the variable $animals. How about using ‘echo $animals;’ instead? Your array of names is permanently lost after you reassigned the variable $animals to hold the value of $_POST[‘animals’]. I think you should check out the following pages for a better grasp of the issue at hand, and ways in which to solve them:

Sponsor our Newsletter | Privacy Policy | Terms of Service