0

I am trying to load data from a variable that contains information and then place them into a string to use on web page using only the space as a divider. I know I have to loop through but I cannot. Shall I perform this in PHP before or use JS to do this? Also is it possible to load up to say 3 at a time? Is it possible to do this? The string looks like this :-

$areas = "London Birmingham Leeds Glasgow Bradford Liverpool Edinburgh etc etc"

and this is how I would like to place the data :-

<h3 class="areas">London</h3>
<h3 class="areas">Birmingham</h3>
<h3 class="areas">Leeds</h3>

or something like :-

<h3 class="areas">London Birmingham, Leeds</h3>

Thanks in advance for any advice.

wayneuk2
  • 156
  • 1
  • 10
  • Use explode to separate the data. http://php.net/manual/de/function.explode.php – DaBra Aug 10 '18 at 10:08
  • 1
    use explode function `print_r (explode(" ",$areas ))`, and also i recommend you to first google your quires – Bilal Ahmed Aug 10 '18 at 10:10
  • Possible duplicate of [Splitting up a string in PHP with every blank space](https://stackoverflow.com/questions/5020202/splitting-up-a-string-in-php-with-every-blank-space) – Bilal Ahmed Aug 10 '18 at 10:12

2 Answers2

2

You do not need any JS to do that, only the explode built-in function :

$areas_list = explode(' ', $areas);

foreach ($areas_list as $area) {
    echo '<h3 class="areas">' . $area . '</h3>';
}
gogaz
  • 2,323
  • 2
  • 23
  • 31
1

You can simply explode() your String into an Array and loop through it :

$areas = "London Birmingham Leeds Glasgow Bradford Liverpool Edinburgh etc etc";

foreach(explode(' ',$areas) as $area){
  echo '<h3 class="areas">'.$area.'</h3>';
}
Zenoo
  • 12,670
  • 4
  • 45
  • 69