0

I have a select drop down list of languages and I'm intrested of putting each element of the array in diffrent variable. For you understanding my question I will put here a code:

<html dir="ltl">
<?php
header('Content-Type: text/html; charset=utf-8');
$db=mysqli_connect("localhost","root","","travelersdb");
mysqli_query($db,"SET NAMES 'utf8'");
?>

    <head>
            <link href="Styles/StyleEx.css" rel="stylesheet" type="text/css"/>
    </head>

    <script type="text/javascript">

         var expanded = false;

        function showCheckboxes() {
          var checkboxes = document.getElementById("checkboxes");
          if (!expanded) {
            checkboxes.style.display = "block";
            expanded = true;
          } else {
            checkboxes.style.display = "none";
            expanded = false;
          }
        }   
        </script> 
<body>


<tr>
      <td>Languages</td>
      <td dir="rtl">

          <form method="post" action="exxx.php">
          <div class="multiselect" dir="rtl">
          <div class="selectBox" onclick="showCheckboxes()" dir="rtl">
        <select>
        <option>Choose language:</option>
        </select>
        <div class="overSelect" dir="rtl"></div>
        </div>
        <div id="checkboxes">
        <label for="one">  
            <input type="checkbox"  id="one" name="languages[]" value="English">English</label>
            <label for="two">
            <input type="checkbox" id="two" name="languages[]" value="German" >German</label>
            <label for="three">
            <input type="checkbox" id="three" name="languages[]" value="French">French</label>
              <label for="four">
            <input type="checkbox" id="four" name="languages[]" value="Spanish">Spanish</label>
              <label for="five">
            <input type="checkbox" id="five" name="languages[]" value="Italien">Italien</label>
      </div>
  </div>  
              <input type="submit" name="submit">
          </form>

      </td>
      </tr>        

<?php

  if (isset($_POST['submit'])) {
 $languages = $_POST['languages'];


    $language1 =  $languages[0];
    $language2 =  $languages[1];
    $language3 =  $languages[2];
    $language4 =  $languages[3];
    $language5 =  $languages[4];

    echo $language1;
    echo $language2;
    echo $language3;
    echo $language4;
    echo $language5;
  }
?>

</body>
</html>

If I'm checking all the checkboxs there isn't a problem but if I'm checking less then 5 I will get this message:

Notice: Undefined offset: 

This is beacuse of the array size. How can I avoid this and echo the variables if there were less than 5 languages checked?

LF00
  • 27,015
  • 29
  • 156
  • 295
Toto88
  • 129
  • 3
  • 11
  • This is not a good practice. Just use a simple `foreach` loop to iterate over your language array. If you cast every language item into a single var, you 'll never know, if a variable exists. Let 's say your language post array contains three entries. So your ´$language4´ and ´$language5´ variables would be never created. This makes code unecessary complecated. As I said, just use a simple foreach loop. – Marcel Apr 28 '17 at 07:11

7 Answers7

2

You can use $$ to define a variable. check the live demo

Note you can access all the variable outside the foreach scope.

foreach($languages as $k => $v)
{
  $name = 'language' . ($k + 1);
  $$name = $v;
}

print_r($language1);
LF00
  • 27,015
  • 29
  • 156
  • 295
1

Use loop. Simplest one would be foreach.

<?php
foreach ($_POST['languages'] as $lang) {
    echo $lang;
}
?>

since $_POST['languages'] is an array, you can loop through all of its elements. No matter how many are there. You even don't have to check if there are any elements at all, if there are none, foreach will be omitted.

Deus777
  • 1,816
  • 1
  • 20
  • 18
0

you can try this, foreach loop is better way to show/process arrays

if(!empty($_POST['languages']){
   $languages = $_POST['languages'];
   foreach($languages as $lang){
    echo $lang;
   }
}
Pragnesh Chauhan
  • 8,363
  • 9
  • 42
  • 53
0

You should loop through the languages and create a variable variable.

for($i = 0, $cnt = count($languages); $i < $cnt; $i++) {
    $name = sprintf("language%d",$i+1);
    ${$name} = $languages[$i];
}

It will create $language1, $language2,.., but will create as many as the number of elements in the array(so it will create only 3 if 3 was checked)

katona.abel
  • 771
  • 4
  • 12
0

Try this..

  if (isset($_POST['submit'])) {
    if(count($_POST['languages'])>0){
        foreach($_POST['languages'] as $key=>$val){
            echo $val;
        }
    }
  }
Ashok
  • 128
  • 1
  • 8
0

Using the advice from the answers above, I'd add the idea to use "variable variables" to allow you to name the individual variables from the $_POST array as they come in. To learn more about this technique, read the PHP documentation Also, be aware that there's an injection attack risk with this technique, so you need to have a way of checking that the elements from $_POST are what you're expecting.

0

The proper way of doing this is using extract function. First you need to store in array where keys will be the name of variable and values will be the values of variable.

Try this code snippet here

<?php

ini_set('display_errors', 1);
$array=array();
foreach($languages as $key => $language)
{
    $array["language".($key+1)]=$language;
}
extract($array);
echo $language1;
echo $language2;
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42