Foreach returning unconverted array

6

I'm using this little code to pick up words with a minimum of 2 characters, but it returns me:

  

Notice: Array to string conversion in echo $ word;

preg_match_all("/[a-z0-9\-]{2,}/i", "oi voce tem problema pra entender isso?", $output_array);

foreach($output_array as $word) {
    echo $word;
}

It should return: oi, voce, tem, problema, pra, entender, isso

    
asked by user3163662 14.01.2015 в 00:05

3 answers

4

The preg_match_all function returns a% multi-dimensional%, the amount of subarrays is proportional to the number of groups in the regular expression, such as mentioned by bfavaretto in comment .

To access the result, enter the subarray index, which in this case is 0 .

$string = 'oi, voce, tem, problema, pra, entender, isso?';

if (preg_match_all("/[a-z0-9\-\,]{2,}/", $string, $output_array) !== false) {
    foreach($output_array[0] as $word) {
        echo $word;
    }
}
// oi,voce,tem,problema,pra,entender,isso

See DEMO

    
14.01.2015 / 00:10
3

From the PHP documentation:

  

So, $ out [0] contains array of strings that matched full pattern, and $ out [1] contains array of strings enclosed by tags.

This means that in its variable $output_array the index 0 represents an array of strings containing the values found that close with the complete regular expression. Already in the index 1 is another array of strings containing the values found that close with the expressions delimited by tags (the parentheses).

For example, see the code below.

preg_match_all("/.*(World).*/", "Hello World", $out);

The result of $out will be:

Array (
    [0] => Array (
            [0] => Hello World
        )
    [1] => Array (
            [0] => World
        )
)

Finally, what you want is to go through the array that closes with the complete expression.

foreach($output_array[0] as $word) {
    echo $word;
}
    
15.01.2015 в 14:55
2

You have to declare the array appropriately, eg:

<?php 
$someArray = array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){ 
    echo $value . "<br />\n";
}
?>
    
14.01.2015 в 00:09