1-Using json_encode on a string results in unwanted slashes in PHP. You would expect a warning would be thrown, but no. This is a frustrating  pitfall, as when you try to read variables, they are always null or curly brackets. So, instead of

{“gender”:”male”,”locale”:”EN_en”}
you get
{\”gender\”:\”male\”,\”locale\”:\”EN_en\”}.


#correct form

$str = json_encode($array);

$arr = json_decode($string, true);

#wrong form

$str = json_encode($mystring);

$arr = json_decode($myarray,true);
#if you are not sure which type is your variable.
echo "
Your variable is ".gettype($mystring)." type

";

2-Do not modify an array while you are looping in it.


#wrong form

foreach($myarray as $index = > $value){
   if($value==3){
      $myarray[$index]=0;
   }
}
#correct form
$dummy = $myarray;
foreach($array as $index = > $value){
   if($value==3){
      $dummy[$index]=0;
   }
}
$myarray = $dummy;

3-Unset problems with local variable
If you pass a variable to a function, and unset it there, the variable is unset for the function. The variable is not unset in the place you called the function.


#wrong form
$var = array();
$var[0]= "I am here";
emptyThis($var);
echo "not unset:{$var[0]}";
function emptyThis($toUnset){
   unset($toUnset);
   echo "only unset for the emptyThis function";
}
#correct form
$var = array();
$var[0]= "I am here";
emptyThis($var);
echo "not unset:{$var[0]}";
unset($var);
echo "Now, it is unset:{$var[0]}";
function emptyThis($toUnset){
   unset($toUnset);
   echo "only unset for the emptyThis function";
}

How to delete an element from array by its value? from dev-tips.com

if(array_search($value,$array) !== false){
    unset($array[array_search($value,$array)]);
}
Advertisements