PHP

WAYS TO CONVERT STRING TO ARRAY IN PHP

THE STRING $thestring = "FOOBAR";   SPLIT ALL CHARACTERS $thearray = str_split($thestring); print_r($thearray); F, O, O, B, A, R

STRING SPLIT

01

THE STRING $thestring = "FOO-BAR";   SPLIT BY GIVEN CHARACTER $thearray = explode("-", $thestring); print_r($thearray); FOO, BAR

EXPLODE STRING

02

THE STRING $thestring = "FOO BAR, HELLO";   SPLIT BY GIVEN PATTERN $thearray = preg_split("/(\s|,\s)/", $thestring); print_r($thearray); FOO, BAR, HELLO

PREG SPLIT

03

THE STRING $str = "Foo Bar, hello";   SPLIT BY POSITION & WORD $thearray = str_word_count($str, 2); print_r($thearray); 0 - Foo, 4 - Bar,  9 - hello

STRING WORD COUNT

04

THE STRING $thestring = "FOO-BAR";   MANUAL LOOP & SPLIT $thearray = []; for ($i=0; $i<strlen($thestring); $i++) {   if ($thestring[$i] != "-")   { $thearray[] = $thestring[$i]; } } F, O, O, B, A, R print_r($thearray);

MANUAL LOOP

05

JSON ENCODED STRING $thestring = '["Red","Green","Blue"]';   JSON DECODE $thearray = json_decode($thestring); print_r($thearray); Red, Green, Blue

JSON DECODE

06

SERIALIZED STRING $thestring = 'a:3:{i:0;s:3:"Red";i:1;s: 5:"Green";i:2;s:4:"Blue";}';   UNSERIALIZE $thearray = unserialize($thestring); print_r($thearray); Red, Green, Blue

UNSERIALIZE

07