Reputation: 259
HI i am trying to convert javascript code to php.below is the javascript code
<script>
var prefs = '["w",32,"r","s",2,"w",65,"w",26,"w",45,"w",24,"w",40,"s",2]';
var si = "hellocode";
var sig = (si + "").split("");
function swap(arr, b) {
l3 = arr[0];
l4 = arr[b % arr.length];
arr[0] = l4;
arr[b] = l3;
return arr
}
var cmd = JSON.parse(prefs||'["r","r"]');
cmd.forEach(function (c, i) {
if (typeof c !== "string") {
return;
}
switch (c) {
case "r":
sig = sig.reverse();
break;
case "s":
sig = sig.slice(cmd[i+1]);
break;
case "w":
sig = swap(sig, cmd[i+1]);
break;
}
});
</script>
What i have tried so far in php
<?php
$prefs = '["w",32,"r","s",2,"w",65,"w",26,"w",45,"w",24,"w",40,"s",2]';
$si = "hellocode";
$arr = str_split($si);
$sig = implode(',', $arr);
function swap($arr, $b) {
$cool = explode(",",$arr);
$l3 = $cool[0];
$l4 = $cool[$b % length($cool)];
$cool[0] = $l4;
$cool[$b] =$l3;
return $cool;
}
// $cool = json_decode($prefs||'["r","r"]');
//now i am struck with converting $prefs to array
$i=0;
foreach($cool as $c)
{
// how to get type of string here ?
// And what does slice function do ?
}
I got struck in 2nd part ? please see the comments and some experts in js to php ..guide me please.:)
Upvotes: 2
Views: 1862
Reputation: 9150
In PHP you have is_string
to check if a variable is a string.
slice
extracts a part of an array (in JS), the PHP pendant is array_slice
when working with arrays or substr
when working with strings.
You found json_decode
already, so just take a look at the examples in the manual.
You max have to split prefs||'["r","r"]'
into an if-else
to check if prefs
isn't empty, but i don't know how PHP handles the or-operator in this case.
To convert the .forEach
from JS to PHP, i wouldn't go for a foreach(...)
, as you won't have access to i
as in the JS callback. Utilize a simple for-loop here.
for($i = 0; $i < count($cool); $i++) { /*....*/ }
Upvotes: 1