Given your string, you can modify it in a simple way with array_map
$string="John Smith - Clearner - 1234$Bob Dillan - IT Man - 2453242$Sarah Clifford - Admin - 32423423"
If foreach is too difficult to grasp, as you have to modify the array you are traversing, try the functional approach, maybe it will result simpler to you.
explode, as you already know create an array splitting the input string with a separator:
$partial= explode("$", $string);
will result in
$partial= [
"John Smith - Clearner - 1234",
"Bob Dillan - IT Man - 245324",
"Sarah Clifford - Admin - 32423423"
];
you can apply the same transformation to every element in an array with array_map. The transformation is encoded into an helper function:
function detail_splitter($string) {
return explode(" - ", $string)
}
that can be leveraged as
$result =array_map(detail_splitter, $partial);
and the result will be:
$result = [
["John Smith", "Clearner", "1234"],
["Bob Dillan", "IT Man", "245324"],
["Sarah Clifford", "Admin", "32423423"]
];
which is an array of array. Every element of the array is processed by the helper function and splitted into a three elements array. The result is used to create a new array with the processed values ready to be further processed.
Obviously you can combine the steps into a single statement:
$result = array_map(
function ($p) { return explode(" - ", $p); },
explode("$", $string);
);
Since now you do not have to transform the array further, but perform a task for every array element you can revert to foreach.
Note that I changed the parameter name from $string to $p to avoid to mess with the scope (for php it will just be fine, human programmers sometimes are not at ease with shadowing variable names).
There is a function, array_walk to perform a task on every element of an array but i think this task would be easier using a simple foreach.
You can address the different persons in a such way:
// $dbc is your db connection
$sql = "INSERT INTO yourtable VALUES (?,?,?);
foreach($result as $person) {
$stmt = $dbc->prepare($sql);
$stmt->bind_param('s', $person[0]);
$stmt->bind_param('s', $person[1]);
$stmt->bind_param('s', $person[2]);
$stmt->execute();
}
I made some assumption with your sql statement but the mysql use it out of the scope of this question, I guess.