Function does not remove array elements

0

Within PHP I add two arrays and then I add them to a variable of a print with JS.

<?php
$objp = array();    
$objs = array();

print("<SCRIPT language=javascript> 
         objp = \"$objp\";
         objs = \"$objs\";
         n_p = new Array (10);
         </SCRIPT>");   
?>

Now within JavaScript I use a for when I submit to add the content of these two arrays within n_p ;

<script language="javascript">

    for(var i = 0; i < 10; i++){
        if(objp!=''){
            n_p[i] = objp;
            objp.shift();
        }
        else{
            n_p[i] = objs;
            objs.shift();
        }   
    }
</script>

The problem is: I am using shift() to remove the first element from array , but when it enters within if it does not execute. What may be the problem? The objs.shift(); function is not executed!

I used the splice () but it did not work too!

    
asked by anonymous 10.10.2014 / 16:30

1 answer

2

Your variables objp and objs in JavaScript are not arrays, they are strings. PHP will simply issue "Array()" to them. Your PHP would need to look like this:

print("<SCRIPT language=javascript> 
     objp = " . json_encode($objp) . ";
     objs = " . json_encode($objs) . ";
     n_p = new Array (10);
     </SCRIPT>");

Assuming I understood what you intended with the JavaScript loop, it should look like this:

for(var i = 0; i < 10; i++){
    if(objp[i] != ''){
        n_p[i] = objp[i];
        objp.splice(i, 1);
    }
    else{
        n_p[i] = objs[i];
        objs.splice(i, 1);;
    }   
}
    
10.10.2014 / 16:34