简体   繁体   中英

Looping through an Array in Javascript from a PHP Array

I have an Array in a PHP variable called: $TillArray

I want to pass this value to a Javascript function and display an Alert for each item in the array.

Here is my code:

<script type="text/javascript">
    ArrayFunction(<?= $TillArray ?>);
</script>

Here is the function code:

function ArrayFunction(MyArray)
{
    for (var i = 0; i < MyArray.length; i++) 
    {
        alert(MyArray[i]);
    }
}

The function displays an "Undefined" message.

Can I please have some help to get this working?

Because you can't do that. You'd have to make the array loopable by JS by turning it into an array that JS can use. You could turn it into JSON, but that depends on how you created the array. If all indexes were numerical, json_encode will turn it into a JS array and any of the 3 basic loops could iterate over it. But if its an associative array, it will turn it into a JS object and you will have to use the for-in loop.

ArrayFunction(<?= json_encode($TillArray) ?>);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM