0

I have a from input that contains series of numbers separate by white space that looks like this:

$input = "1243 984 4692 9465 ";

Is there any way to convert this to an array that keeps those numbers like this looks like this:

$array_numbers[0] = 1243 
$array_numbers[1] = 984 
$array_numbers[2] = 4692
$array_numbers[3] = 9465

Any help on this will be much appreciated,

Thank you

huysentruitw
  • 27,376
  • 9
  • 90
  • 133
user3277558
  • 15
  • 1
  • 2

3 Answers3

4

Try

$array_numbers = explode(' ', trim($input));
Ali Shan
  • 628
  • 5
  • 17
2

Trim and explode will do that for you.

http://php.net/manual/en/function.explode.php

http://php.net/manual/en/function.trim.php

Trim removes the whitespace at the end, which if it stays will cause an empty entry in the array.

$input = "1243 984 4692 9465 ";
$array_numbers = explode(' ', trim($input));
user5542121
  • 1,051
  • 12
  • 28
2

The best way to do this is to use the explode function in php that separate the content of your string into an array of string, then convert each elements of array items into integer using intVal() function in php See sample code below

<?php
     $hello = "12 34 45 56 78";
     $result = array();
     $result = explode(" ", $hello);
     for($j=0; $j<count($result); $j++){    
         echo intval( $result[$j] )."</br>";
    }
?>
Babajide Apata
  • 671
  • 6
  • 18