Jump to content

pick a name from a number


Revolutsio

Recommended Posts

I have five names in an array and also numbers 5,2,1,3 and what i want to do is php to look at the numbers and print out the name that corresponds to the number.

so for my example the name it should echo out is 'Lee'

 

 $names = array ("Stan", "John", "Dean", "Sam", "Lee");

here are the five names.

The idea is to learn php with making a little fixture list with these five names.

The problem i have is to make php read the number and then look up the array for the name that corresponds to the number.

I hope this explains what I would like to do?

 

Link to comment
Share on other sites

So basically, you are looking to loop through an array of numbers. For each number, you want to display the name that corresponds with that number. So in your loop, when you get to 5, it should display "Lee". And 2 should be "John". Correct?

If so, where are you stuck? What have you tried so far? Be aware that PHP arrays don't start with 1 for the index, by default.

Edited by cyberRobot
fixed typo
Link to comment
Share on other sites

Also, can I ask what's going on here:

$num1 = (5);

Is there a reason for the parentheses? Apparently PHP doesn't care if they are there. PHP appears to ignore them. Unless there is a reason for using the parentheses, it would be clearer to use the following:

$num1 = 5;

 

Edited by cyberRobot
fixed typo
Link to comment
Share on other sites

If you define your array like this, to begin the indexing at 1 instead of 0,

$names = array (1 => "Stan", "John", "Dean", "Sam", "Lee");

then your indexes will align with your $num values, 1 - 5; In other words

$num = 5;
echo $names[$num];              //--> Lee

That will save you doing what ginerjm is about to tell you to do :)

Edited by Barand
Link to comment
Share on other sites

35 minutes ago, Barand said:

If you define your array like this, to begin the indexing at 1 instead of 0,


$names = array (1 => "Stan", "John", "Dean", "Sam", "Lee");

then your indexes will align with your $num values, 1 - 5; In other words


$num = 5;
echo $names[$num];              //--> Lee

 

Once again @Barand you come to me rescue thanks again

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.