Dayz
Dayz

Reputation: 269

Explode string on commas and pipes to create two arrays

I did coding as below and got the wrong output:

$asst_vicars_data_arr=explode(',',$asst_vicars_data);
$asst_head_type_count=count($asst_vicars_data_arr);

$d = explode("|",$data);
foreach ($asst_vicars_data_arr as $value) {
    $arr = explode("|",$value);
    print_r($arr); 
}

Input:

$asst_vicars_data_arr=Array ( [0] => PT|1 [1] => O|4 [2] => PT|15,... )

Expected output:

$type=Array([0] => PT, [1] => O,...)
$heads=Array([0] => 1, [1] => 4,...)

What can I do to create these two arrays?

Upvotes: 4

Views: 1011

Answers (3)

mickmackusa
mickmackusa

Reputation: 48031

At its core, this question is a string to array conversion exercise. Rather than doing a whole bunch of explode()'s, let's investigate a couple of methods that will do fewer iterated function calls...

Method #1: One-liner using preg_match() and array destructuring:

preg_match_all('/([^|]+)\|([^,]+)/', $asst_vicars_data, $m) ? [, $type, $heads] = $m : null;
// output: $type=array(0=>'PT', 1=>'O', 2=>'PT')
// output: $heads=array(0=>'1', 1=>'4', 2=>'15')

Method #2: 3-liner using preg_split(), array_chunk(), and array_column()

$asst_vicars_data = 'PT|1,O|4,PT|15';
$a = array_chunk(preg_split('/,|\|/', $asst_vicars_data), 2);
$type = array_column($a, 0);  // output: array(0=>'PT', 1=>'O', 2=>'PT')
$heads = array_column($a, 1); // output: array(0=>'1', 1=>'4', 2=>'15')

My first method uses a lean regex pattern to extract the values which list() easily sets to variables. list()'s leading comma means that the first subarray (the full strings) of $m will not be assigned a variable name.

My second method uses a lean regex pattern to explode the string on pipes and commas in the same step. array_chunk() puts the elements in pairs. Finally array_column() gets the "vertical" values in array.

All other answers currently on this page are using explode() calls on every iteration. This approach becomes increasingly inefficient as the size of the input grows. For this reason, it is going to be more efficient to carry out all exploding/splitting once and move forward from there.

Method #1 is clearly my favorite method for this case; I only wanted to show Method #2 as an alternative which also dissects the string just once before processing the pieces.


Here are some additional methods that behave like the foreach loops in other answers (they also suffer from the same inefficiency because they call explode() on every iteration):

array_map() can be abused to write a ugly little one-liner:

$asst_vicars_data = 'PT|1,O|4,PT|15';
array_map(function($a) use(&$type, &$heads) { [$type[], $heads[]] = explode('|', $a); }, explode(',', $asst_vicars_data));
var_export($type);
var_export($heads);

Same story with array_walk() but with an extra line of code:

$asst_vicars_data = 'PT|1,O|4,PT|15';
$asst_vicars_data_arr = explode(',', $asst_vicars_data);
array_walk($asst_vicars_data_arr, function($a) use(&$type, &$heads) { [$type[], $heads[]] = explode('|', $a); });
var_export($type);
var_export($heads);

Upvotes: 3

Sahil Gulati
Sahil Gulati

Reputation: 15141

I hope this will help you out, Here i am using explode to break a string and foreach loop.

Try this code snippet here

<?php

ini_set('display_errors', 1);
$asst_vicars_data_arr=Array ( 0 => "PT|1",
                              1 => "O|4",
                              2 => "PT|15",
                              3 =>"1|6");
$types=array();
$heads=array();
foreach($asst_vicars_data_arr as $value)
{
    list($types[],$heads[])=explode("|",$value);
}

print_r($types);
print_r($heads);

Upvotes: 3

Nishant Nair
Nishant Nair

Reputation: 1997

You can try this out

<?php
$asst_vicars_data_arr=array ( 0 => 'PT|1' , 1 => 'O|4' , 2 =>'PT|15');
foreach ($asst_vicars_data_arr as $value) {
    $arr = explode("|",$value);
    $type [] = $arr[0];
    $heads [] = $arr[1];
}
print_r($type);
print_r($heads);
?>

Fiddle

Upvotes: 3

Related Questions