Skip to content
Advertisement

How to work json string on foreach loop in php

I’m trying to make a foreach loop from string value which comes from a JSON value like:

string '["userdomain.ltd"], ["test.com"]'

I want to make a foreach loop and echo URL under the loop

I have tried using this but it returns PHP Warning: Invalid argument supplied for foreach()

foreach( $device_url as $url ){
    echo $url;
}

Advertisement

Answer

Your input is a string, so we need transform it to array for iterate:

<?php
$str = '["userdomain.ltd"], ["test.com"]';

$arr = explode(',', $str);

foreach ($arr as $el) {
    echo json_decode($el)[0];
    echo "n";
}

Here you can try working code: PHPize.online

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement