I want to convert this array that Array[4] should not give null it can give blank space (empty string).
Array (
[0] => 1
[1] => 4
[2] =>
Use this function. This will replace null to empty string in nested array also
$arr = array(
"key1"=>"value1",
"key2"=>null,
"key3"=>array(
"subkey1"=>null,
"subkey2"=>"subvalue2"),
"key4"=>null);
echo json_encode(replace_null_with_empty_string($arr));
function replace_null_with_empty_string($array)
{
foreach ($array as $key => $value)
{
if(is_array($value))
$array[$key] = replace_null_with_empty_string($value);
else
{
if (is_null($value))
$array[$key] = "";
}
}
return $array;
}
Output will be :
{
"key1": "value1",
"key2": "",
"key3": {
"subkey1": "",
"subkey2": "subvalue2"
},
"key4": ""
}
Try online here : https://3v4l.org/7uXTL
PHP 5.3+
$array = array_map(function($v){
return (is_null($v)) ? "" : $v;
},$array);
Here's a technique I haven't seen mentioned in the above answers:
$val = strval(@$arr["notfound"]); // will not generate errors and
// defaults to an empty string
This is super handy for $_GET parameter loading to keep things short and readable. Bonus, you can replace strval() with trim() ... or with intval() if you only accept integers.
The default for intval will be 0 if missing or a non-numeric value. The default for strval is "" if empty, null or false.
$val_str = strval(@$_GET['q']);
$val_int = intval(@$_GET['offset']);
See DEMO
Now for an array, you'll still need to loop over every value and set it. But it's very readable, IMO:
$arr = Array (1, 4, "0", "V", null, false, true, 'true', "N");
foreach ($arr as $key=>$value) {
$arr[$key] = strval($value);
}
echo ("['".implode("','", $arr)."']");
Here is the result:
['1','4','0','V','','','1','true','N']
Interesting is that true becomes "1", but 'true' stays a string and that false becomes and empty string "".
Now the same data using $arr[$key] = intval($value); produces this result:
['1','4','0','0','0','0','1','0','0']