Dear friends today we will learn about PHP arrays. We often need to select records from database. There are different methods to select data from Database. But today we will learn something difficult.
Suppose you have following string data that you want to convert into an array to perform action on it:
$string = “one,two,three,four”;
and you need to convert it into:
$string_array = array(“one”,”two”,”three”,”four”);
You need to write a function with PHP’s explode function for easy job.
Write following function
function comma_separated_to_array($string_value, $separator = ',')
//Explode on comma
$vals = explode($separator, $string_value);
$count = count($vals);
$val = array();
$val .= $vals[$i];
You wrote a function where you used explode function and then with the use of count function and for loop you add all exploded values into an array and then return it. Now you can use this function any where, but remember you have to pass minimum 1 parameter to function which is $string value. 2nd parameter is optional.
Hope you enjoyed the tutorials. See you in the next tutorial.