0

I am trying to return array strings based on position, concatenate and append into a new array.

$matches = ([0] => 20170623 004129 982 a [4] => 20170623 004130 982 b [8] => 
            20170623 004130 982 b)
foreach ($matches as $match){
    $arr2 = explode(" ", $match);
    echo $arr2[0] . $arr2[1] . $arr2[2];

The for loop works for explode and can see each element(strings) of the array being separated into a new array $arr2, but each pass through the loop overwrites $arr2. My echo is returning the same result (the result of the last pass) multiple times. Looks like once for each pass.

Expected output, maybe something like:

$arr3 = ([0] => 20170623004129982 [1] => 20170623004130982 [3] => 
            20170623004130982)
1
  • Could we maybe see some data, current output and the expected output? Commented Jun 23, 2017 at 13:57

2 Answers 2

1

create an array above foreach, so it will not reinitialize with each iteration as, and add the values in it which each iteration

$arr=[];
foreach ($matches as $match){
    $arr2 = explode(" ", $match);
    array_push($arr,array_map(function($arr2){
         return $arr2;
    },$arr2));
    echo "<pre>";print_r($arr);
}
Sign up to request clarification or add additional context in comments.

Comments

0

You need array_push()

In your case

<?php
    $arr2 = [];
    foreach ($matches as $match) {
        $values = explode(" ", $match);
        array_push($arr2, $values[0], $values[1], $values[2]);   
    }

    var_dump($arr2); // now $arr2 should contain all values
?>

8 Comments

it will push the whole arry, not the array values
@RAUSHANKUMAR thanks for comment! Updated the answer
add the index 1
it's ok, better run your code in fiddle with static data, and then answer here, it will helpful for others
This concatenates everything into a long array. So I get... [0]=> string(8) "20170623" [1]=> string(6) "004129" [2]=> string(8) "20170623" [3]=> string(6) "004129" [4]=> string(3) "982" [5]=> string(8) "20170623" [6]=> string(6) "004129" [7]=> string(3) "982" See my expected results above: $arr3 = ([0] => 20170623004129982 [1] => 20170623004130982 [3] => 20170623004130982)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.