Turning an PHP variable into an array

2

I have a JavaScript variable that is a string "13:00:00" , however I would like to pass it to PHP and slice it into an array, separating it with ":" but the explode function does not work with the following code :

<script>

    fin = "02:00:00";

    </script>
</head>
<body>
    <?php
    $fin = "<script>document.write(fin)</script>";       

    $tfin = explode(":", $fin);

    echo "<pre>";        
    var_dump($tfin);
    echo "</pre>";

    ?>


</body>  

How do I proceed to slice this string?

    
asked by anonymous 15.09.2015 / 02:11

2 answers

2

PHP is a server language, that is, the script is sent to the server, it is processed and then returns the output result, since the javascript is a client language, it is not sent to the server to process, so you can not capture this way you want unless you use the value already processed via GET, PUT, POST or making a PARSE of the document itself. How can you solve the problem by sending it via AJAX:

  <?php
if(isset($_POST['fin'])) {
$fin = $_POST['fin'];
 $tfin = explode(":", $fin);

    echo "<pre>";        
    var_dump($tfin);
    echo "</pre>";
die();

}
?>

<script src="https://code.jquery.com/jquery-latest.min.js"></script><script>$(function(){varfin="02:00:00";
       var data = {fin:fin};
       $.post('<?php echo $_SERVER["SCRIPT_NAME"]; ?>', data, function(e) { 
        document.write('<html><body>'+e+'</body></html>');
       });
    });
 </script>

Another way to use the explode of javascript, the split() function:

 <body></body>
      <script>
      var fin = "02:00:00";
        var arrFin = fin.split(":");
        var out = '';
        for (var i in arrFin) {
            out += i + ' <font color="#888a85">=&gt;</font>'+
            ' <small>'+ typeof arrFin[i] +"</small> "+
            "<font color=\"#cc0000\">'" + 
            arrFin[i] + 
            "'</font> <i>(length="+arrFin[i].length+")</i>\n";
        }
        var pre = document.createElement('pre');
        pre.setAttribute('class','xdebug-var-dump');
        pre.setAttribute('dir','ltr');
        pre.innerHTML = out;
        document.body.appendChild(pre);
     </script>
    
15.09.2015 / 15:18
1

Since your variable is in JavaScript, make replace the same way, be careful with the variable layers.

    <script>
            var fin = "02:00:00";
            res = fin.replace(/\:/g,'.')
            document.getElementById("novotempo").innerHTML = res;
    </script>
<body>
<pre id='novotempo'></pre>
</body>

If you need to pass it to server-side take a look at AJAX methods.

    
15.09.2015 / 02:53