Drenyl
Drenyl

Reputation: 934

How to get each element in array and split them into two variables from a delimiter

How can I get each element in an array, separate them from its delimiter, and store them into two different variables. I can only get the last iteration of my foreach loop. Any answers are fully appreciated.

This is want I wanted to accomplish:

$string1 = array('AL8941786046','AL8941786046');
$string2 = array('464646', '555');

And here is the array that I wanted to work:

Array ( [0] => AL8941786046|464646 [1] => AL8941786046|555 )

First iteration will be this first element AL8941786046|464646, then I separate this first element into two string using explode function. using this line of code

list($string1, $string2) = explode('|', $myArray, 2);

Now I can only get the last iteration only the second element AL8941786046|555

Here is my code:

             $string1 = array();
             $string2 = array();
             $myArray = array('AL8941786046|464646','AL8941786046|555');
             foreach ($myArray as $val) {
                $ars = $val;
                list($string1 , $string2 = explode('|', $val, 2);
             }

Upvotes: 1

Views: 62

Answers (3)

lukassteiner
lukassteiner

Reputation: 847

If you want the elements in the array to build two arrays that contain the first and the second part of the elements, you can do this:

$string1 = [];
$string2 = [];
$myArray = ['AL8941786046|464646', 'AL8941786046|555'];

foreach ($myArray as $val) {
    $exploded = explode('|', $val, 2);

    $string1[] = $exploded[0];
    $string2[] = $exploded[1];
}

This will give you:

enter image description here

Upvotes: -1

Osama
Osama

Reputation: 3040

$string1 =[];
         $string2 =[];
         $myArray =  array('AL8941786046|464646','AL8941786046|555');
         foreach ($myArray as $val) {
            $string1[]=explode(‘|’,$val)[0];
            $string2[]=explode(‘|’,$val)[1];
         }
$array=array_combine($string1,$string2);

Upvotes: 0

Tobia
Tobia

Reputation: 9506

If you want two arrays as result:

         $string1 = [];
         $string2 = [];
         $myArray = array('AL8941786046|464646','AL8941786046|555');
         foreach ($myArray as $val) {
            $arr=explode('|', $val, 2);
            $string1[]=$arr[0];
            $string2[]=$arr[1];
         }

This will be the output:

$string1: Array ( [0] => AL8941786046 [1] => AL8941786046)
$string2: Array ( [0] => 464646 [1] => 555 )

Upvotes: 3

Related Questions