0

How do I Loop through all phrases and output them as a list of links, with GET-parameters?

How do I make an array, indexed with integers then use a GET-variable to choose one of these phrases.

My code so far;

$arr = array('1' => 'Que será, será.', '2' => 'C’est la vie!', '3' => 'Sich nicht um ungelegte Eier kümmern.', '4' => 'Ada asap, ada api.', '5' => 'Batti il ferro finché è caldo.');
?> 

<p><?php print $arr[1]; ?> - Whatever will be, will be.</p>
<p><?php print $arr[2]; ?> – That’s the life.</p> 
<p><?php print $arr[3]; ?> - Don’t count your chickens before they hatch.</p> 
<p><?php print $arr[4]; ?> - There's no smoke without fire.</p> 
<p><?php print $arr[5]; ?> - Strike while the iron is hot.</p>
2
  • The same way you print them: $arr[...], except that ... will be something coming from $_GET. Not directly $_GET['var'] because that's trusting user input too far. Commented Nov 13, 2012 at 10:29
  • Do you have problems with encoding? Why you added "character" tag? Commented Nov 13, 2012 at 10:36

3 Answers 3

2

This should do it:

$key = (int)$_GET['key'];
if (isset($arr[$key]) {
   echo print $arr[$key]; 
} else {
   echo "Invalid option specified";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nobody has mentioned anything about MySQL.
1
<?php  
  $key = mysql_real_escape_string($_GET['value']);//Pass this value from url and sanitize the inputs
  ?>
  <p><?php print $arr[$key]; ?>

Comments

1
$key = $_GET['index'];
$val = isset($arr[$key]) ? $arr[$key] : false;

Edit: Why do people keep recommending mysql_real_escape_string? This is for database query escaping and sends a request to the database (as far as I understand). The key doesn't even need escaping as it's not being sent to the database or output.

1 Comment

Someone pointed this out, for me was just habit, I edited my answer, thank you.

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.