PHP

WAYS TO CONVERT ARRAY TO STRING IN PHP

(quick guide & examples)

THE ARRAY $arr = ["red", "green", "blue"];

IMPLODE ARRAY

01

IMPLODE ARRAY $str = implode(", ", $arr); echo $str; red, green, blue

REDUCTION FUNCTION function reduce ($carry, $i) {   if ($i !="green") { $carry .= "$i, ";  }    return $carry; }

ARRAY REDUCE

02

REDUCE ARRAY $arr = ["red", "green", "blue"]; $str = array_reduce($arr, "reduce"); $str = substr($str, 0, -2); echo $str; red, blue

THE ARRAY $arr = ["red", "green", "blue"];

MANUAL LOOP

03

MANUAL LOOP & COMBINE $str = ""; foreach ($arr as $i) { $str.= "$i, "; } $str = substr($str, 0, -2); echo $str; red, green, blue

THE ARRAY $arr = ["red", "green", "blue"];

JSON ENCODE

04

JSON ENCODE $str = json_encode($arr); echo $str; ["red","green","blue"]

THE ARRAY $arr = ["red", "green", "blue"];

SERIALIZE DATA

05

PHP SERIALIZE $str = serialize($arr); echo $str; a:4:{i:0;s:3:"red";i:1;s:5:"green" ;i:2;s:4:"blue"}