0

I'm trying to loop through an array that I got from preg_match_all result in order to create one string from all results.

Array looks like this:

print_r($matches[0]);


Array
(
    [0] => Array
        (
            [0] => 8147
            [1] => 3
        )

    [1] => Array
        (
            [0] => 8204
            [1] => 20
        )

)

And my code:

$found = count($matches[0]);
for ($i = 0; $i <= $found; $i++) {
    $string = $matches[0][$i];
}

I would like to get result of $string like this: 8147, 8204.

How I can append $matches[0][0] to $matches[0][1] etc. in string variable using loop?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
AdrianM2
  • 3
  • 5

4 Answers4

2

You can do this some ting like that

$string = "";
foreach($matches[0] as $value) {
    $string .= $value[0].", ";
}
$string = rtrim(", ",$string);
Md Hasibur Rahaman
  • 1,041
  • 3
  • 11
  • 34
1

Try following code. Loop through array and get values

$arr =Array
(
    0 => Array
        (
            0 => 8147,
            1 => 3
        ),

    1 => Array
        (
            0 => 8204,
            1 => 20
        )

);
$match_array = array();
foreach($arr as $key=>$value)
{
    $match_array[] = $value[0];
}
$str =  implode(",",$match_array);
echo $str;

DEMO

OR simply use array_column to get specific column as array then use implode

$arr =Array
(
    0 => Array
        (
            0 => 8147,
            1 => 3
        ),

    1 => Array
        (
            0 => 8204,
            1 => 20
        )

);
$match_array = array_column($arr,0);

$str =  implode(",",$match_array);
echo $str;

DEMO

B. Desai
  • 16,414
  • 5
  • 26
  • 47
1

With php5.5 and more you can use array_column + implode:

echo implode(', ', array_column($matches, 0));
u_mulder
  • 54,101
  • 5
  • 48
  • 64
1

You can use array_column, no need to loop over the array

$result = join(',', array_column($arr, 0));
beta-developper
  • 1,689
  • 1
  • 13
  • 24