Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
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?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

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);
over 4 years ago · Santiago Trujillo Relatório

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

over 4 years ago · Santiago Trujillo Relatório

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);
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda