Kyle Van Housen
Kyle Van Housen

Reputation: 85

Accessing parts of a php array in a javascript for loop

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);
}

Upvotes: 1

Views: 37

Answers (1)

Eddie
Eddie

Reputation: 26844

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
    //.........
}

Upvotes: 2

Related Questions