Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
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?

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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);
about 4 years ago · Santiago Trujillo Report

0

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

about 4 years ago · Santiago Trujillo Report

0

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() & list()

preg_match_all('/([^|]+)\|([^,]+),?/',$asst_vicars_data,$m)?list(,$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 used to write a nice little one-liner:

$asst_vicars_data='PT|1,O|4,PT|15';
array_map(function($a)use(&$type,&$heads){list($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){list($type[],$heads[])=explode('|',$a);});
var_export($type);
var_export($heads);
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!