A plugin I use stores multiple values in one string.
var_dump looks like this:
{\"strict\":\"0\",\"thirdparty\":\"1\",\"advanced\":\"0\"}
I need to check if, for example, "advanced" is true or not.
Doing it in php would be great, JS would also be good.
$jsIn = '{\"strict\":\"0\",\"thirdparty\":\"1\",\"advanced\":\"0\"} ';
$jsOut = json_decode(stripslashes($jsIn));
<?php
$input = '{\"strict\":\"0\",\"thirdparty\":\"1\",\"advanced\":\"0\"}';
$input = str_replace('\', '', $input);
$input = json_decode($input, true);
$advanced = empty($input['advanced']);
If your string contains antislashes, you must remove it. Here with PHP#str_replace
after that you decode the json string to have an association array and finally test $input['advanced']
with PHP#empty
that returns false
for false, 0, null, or '0' value otherwise true.
Problem solved and works as intended. So, first we get rid of the backslashes in the string that's the value of this cookie with stripslashes(), in wordpress use wp_unslash(). After json_decode() we have access to (in this case) three items ( strict, thirdparty, advanced ) which can have a value of 0 or 1. Now, in the var_dump() each item contains string(1) before the actual value.
string(1) "1"
string(1) "0"
The IF statement nevertheless works as intended.
$input = json_decode( stripslashes( $_COOKIE['some-cookie'] ), true );
$thirdparty = $input['thirdparty'];
$advanced = $input ['advanced'];
var_dump( $thirdparty );
echo "<br>";
var_dump( $advanced );
echo "<br>";
if ($thirdparty > 0) {
echo "allowed";
} else {
echo "not allowed";
}
echo "<br>";
if ($advanced > 0) {
echo "allowed";
} else {
echo "not allowed";
}
Many thanks to all ...