PHP

Converting Strings to Arrays

$a = explode(',', $csvdata);

Sometimes, arrays are not used to store information; instead, a string is used. The single values are all within the string, but are separated by a special character. One example for this is the comma separated values (CSV) format.

explode function syntax

array explode ( string $delimiter , string $string [, int $limit ] )

explode function splits a string by string and returns an array of strings. This function accepts three parameters:

  1. delimiter a boundary string

  2. string an input string

  3. limit maximum of limit elements with the last element containing the rest of string

Turning a String into an Array

<?php
  $csvdata = 'value 1,value 2,value 3,value 4,value 5';
  $a = explode(',', $csvdata);
  $info = print_r($a, true);
  echo "<pre>$info</pre>";
?>

The PHP function explode() creates an array out of these values; you just have to provide the character(s) at which the string needs to be split. The browser then shows this output:

Array
(
    [0] => value 1
    [1] => value 2
    [2] => value 3
    [3] => value 4
    [4] => value 5
)

by BrainBellupdated
Advertisement: