4

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?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Dayz
  • 269
  • 2
  • 12

3 Answers3

3

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);
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
3

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

Rushil K. Pachchigar
  • 1,263
  • 2
  • 21
  • 40
Nishant Nair
  • 1,999
  • 1
  • 13
  • 18
3

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);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • It would seem that you should have been closing the question I answered as a dupe of this, not the other way around? – Nick Apr 19 '23 at 07:23
  • I believe the dupe target has a better/clearer [mcve] and a good clear accepted answer. This page has unexplained answers which demonstrate splitting elements which have already been split once. The other page is simply better. – mickmackusa Apr 19 '23 at 08:10
  • In that case perhaps you should offer some of these solutions on that page, as the use of array destructuring on the `preg_match` version is an improvement over the other answers – Nick Apr 19 '23 at 08:12
  • Meh. That wouldn't be ethical/decent. I cannot delete my answer. Feel free to add anything from here into yours. I will be treating that page as the canonical for all future dupes on this topic. – mickmackusa Apr 19 '23 at 08:17
  • Well, in that case I might add a note about array destructuring to the preg_match code too then. – Nick Apr 19 '23 at 08:21
  • Interestingly you don't need the conditional on the result of `preg_match_all`. If you just do a straight assignment `[, $type, $heads] = $m`, if there are no matches you will get the expected(?)/desired(?) result of two empty arrays. https://3v4l.org/i8bkA – Nick Apr 19 '23 at 08:31
  • I believe I posted this answer when I was in a phase of thinking if code can be written as a one-liner -- that was the best. Of course I know longer think that way. I'll modernise my advice. – mickmackusa Apr 19 '23 at 20:21