1

I have a string containing values i.e.

'Acton $ 80 Ajax $ 80 Aldershot $ 80 Alliston $ 115 Alton $ 80 Aldershot $ 84 Alexandria $ 674'

I want to make:

<option value='80'> Acton </option>
<option value='80'> Ajax </option>

...and so on. How should I do this, using PHP?

3 Answers 3

2
$str = 'Acton $ 80 Ajax $ 80 Aldershot $ 80 Alliston $ 115 Alton $ 80 Aldershot $ 84 Alexandria $ 674';
$arr = explode(" ", $str);
for($i = 0; $i < count($arr)/3; $i+=3)
    echo "<option value='".$arr[$i]."'>".$arr[$i+2]."</option>\n";

Try explode function. However, this code doesn't handle error input.

Sign up to request clarification or add additional context in comments.

2 Comments

the code seems to work ok but nothing appears arr[$i+2] only the option value is there after so many blanks
Can you describe youre problem more specifically?
1

Working code:-

<?php
$str = 'Acton $ 80 Ajax $ 80 Aldershot $ 80 Alliston $ 115 Alton $ 80 Aldershot $ 84 Alexandria $ 674';
$arr = explode(" ", $str);
?>
<select>
    <?php 
    $i = 0;
    foreach($arr as $key=>$value) {
        if($i == $key) {
            ?>
            <option value="<?php echo $arr[$i+2] ?>"><?php echo $arr[$i] ?></option>
            <?php
            $i = $key+3;
        }       
    }
    ?>
</select>

Hope this helps.

Comments

1
$tmp = explode(' ', $string);

$result = '';
while (!empty($tmp)) {
  $name = array_shift($tmp);
  $dollarSign = array_shift($tmp);
  $value = array_shift($tmp);

  $result .= "<option value='$value'>$name</option>";
}

2 Comments

takes ages to process and timeout error appears on the browser
Except two annoying, but obvious typos: Not reproducable. Its works fine for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.