1

I'm trying to access and display elements of a php array in a javascript for loop, whenever I try and log out a value it always returns blank and I can't figure out why.

for(let i=0;i<"<?php echo sizeof($response['results']); ?>"; i++) {
    console.log(i);

    let divElement = document.createElement("div");
    divElement.className = "col col-6 col-md-4 col-lg-3";
    let h4Name=document.createElement('h4');
    h4Name.className="name";
    h4Name.innerHTML="<?php echo $response['results'][i]['name']?>;"
    console.log("<?php echo $response['results'][i]['name']?>");
    divElement.appendChild(h4Name);
    let h4Address=document.createElement('h4');
    h4Address.className="address";
    h4Address.innerHTML="<?php echo $response['results'][i]['formatted_address']?>";
    divElement.appendChild(h4Address);

    document.querySelector(".row").appendChild(divElement);
}
1

1 Answer 1

2

You can't loop thru a JS array and access a corresponding PHP array. PHP is a back end code and JS (in this case) is a front end code.

One option you have is to have a result variable in javascript and use that array to loop.

Like:

//Put the PHP array into a JS variable
const results = <?php echo json_encode( $response['results'] );?> 

//Loop thru the JS variable 
for (let i = 0; i < results.length; i++) { 
    //Access object property as results[i]['formatted_address'] or results[i].formatted_address
    //.........
}
Sign up to request clarification or add additional context in comments.

1 Comment

Worth mentioning that this also correctly protects from all kinds of JS injections that are possible in the original code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.