conmen
conmen

Reputation: 2417

Populate a 2d array with qualifying data from a multi-line txt file containing comma-separated values

Below script is shown search string in a text file, my text file has contents like:

60, 1, 1, 188, pdgje5566

60, 1, 1, 188, pdgje5565

if(!empty($extTxId)){
$searchfor = $extTxId;

$matches = array();

$handle = @fopen($file, "r");
if ($handle)
{
    while (!feof($handle))
    {
        $buffer = fgets($handle);
        if(strpos($buffer, $searchfor) !== FALSE)
            $matches[] = $buffer;
    }
    fclose($handle);
}

print_r($matches);

it output as

Array ( [0] => 60, 1, 1, 188, ppje5566 )

However, I want to explode the data which is separate by comma(,) and store into variable, is that anyway to do it?

Upvotes: 0

Views: 2759

Answers (4)

Kęstutis
Kęstutis

Reputation: 1061

If you know the exact structure of the input you're getting, you could do something like:

$string = '60, 1, 1, 188, pdgje5565';
// Using trim just to be sure
list($varA, $varB, $varC, $varD, $varE) = explode(', ', trim($string));

This way you would get the results as follows:

$varA = 60;
$varB = 1;
$varC = 1;
$varD = 188;
$varE = 'pdgje5565';

The main advantage here is you would get decent variables instead of array with abstract indexes, but it is only good if you're sure about you're structure being constant.

Upvotes: 0

Jason McCreary
Jason McCreary

Reputation: 72961

i want to explode the data which is separate by comma(,)

Use explode().

If this is a CSV file (or some other delimited file), I suggest looking at fgetcsv(). It is effectively fgets() and explode(), which seems to be what you need.

Upvotes: 4

wesside
wesside

Reputation: 5740

Since you have spaces between each comma, you can trim each element.

// Iterate through each item int the array (you can do $matches[0] if you just want the first)
foreach ($matches as $match)
{
     $output_array = array_map('trim',explode(',',$match));

     print_r($output_array);
}

Output:

Array
(
    [0] => 60
    [1] => 1
    [2] => 1
    [3] => 188
    [4] => pdgje5565
)

Example: http://codepad.org/aSyVX5Bj

Upvotes: 2

GautamD31
GautamD31

Reputation: 28763

Try like

foreach(Array[0] as $element)
{
     echo $element;
}

Upvotes: 0

Related Questions