Split a variable into an Array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • OakleyUK
    New Member
    • Jan 2012
    • 1

    Split a variable into an Array

    I'm trying to split a list of numbers separated by a comma into an array, which i can then loop through and execute a command for each number in the list.

    So what i really want to achieve is this;

    $numbers = "2564521,545125 4"
    $data = array($numbers)

    However this will not work with an array.

    This is what i have so far;

    Code:
    $data = array(2564521,5451254);
    
    //Our 'stepping' variable
    $g = 0;
    
    //Our rowcount
    $rowcount = 0;
    
    echo "<table cellspacing='0'>\r";
        for ($i=0; $i<count($data); ) {
    
            $rowcount++;
            echo "    <tr>\r"; //New row
    
            $g = $i + 3; //Set our nested limit
            for( ; $i<$g; $i++) { //nested for loop
    
                if (!isset($data[$i])) { //Allow us to break on incomplete rows
                    break;
                }
    
                echo "        <td style='border: 1px #000 solid;'>\r"; //Out put a cell
                echo "         Number: $data[$i]</p>\r";
                echo "        </td>\r";
    			echo "$data[$i]</p>\r";
    			
    			$tonumbers = "$data[$i]";
    			
    //Execute command for each number
    
    			
            }
    
            echo "    </tr> \r"; //End New Row
        }
    
    echo "</table>\r";?>
    I would appreciate any help, thanks!
  • charles07
    New Member
    • Dec 2011
    • 45

    #2
    use php explode

    PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites in the world.


    or php str_split

    PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites in the world.
    Last edited by Dormilich; Jan 16 '12, 06:16 AM.

    Comment

    • Bharat383
      New Member
      • Aug 2011
      • 93

      #3
      $numbers = "2564521,545125 4";

      $temp_array = explode(",",$nu mbers);

      you can get $temp_array[0] = 2564521 and $temp_array[1] = 5451254

      Comment

      Working...