Foreach returning unconverted array

Asked

Viewed 229 times

6

I’m using this little code to capture words with minimum 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;
}

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

3 answers

4


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

To access the result, enter the index of subarray, 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

  • @bfavaretto What’s up? I removed the usefulness and improved the answer a little bit, Sorry the delay. :)

  • Imagine, not even two years :P I had already voted at the time.

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.

That means in your variable $output_array the index 0 represents an array of strings containing the values found that close with the full regular expression. Already in the index 1 is another string array containing the values found that close with tags delimited expressions (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 full expression.

foreach($output_array[0] as $word) {
    echo $word;
}

2

You have to declare the array appropriately, example:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.