A PHP function can accept an array argument and can return an array. Modern PHP can also declare array parameter and return types where appropriate.
function words(string $text): array {
return explode(' ', trim($text));
}
$result = words('Hello welcome to plus2net');
foreach ($result as $key => $value) {
echo "$key -> $value
";
}The old split() and each() functions are removed from current PHP; use explode()/preg_split() and foreach instead.
explode() and create an array. This array we will return to main script for displaying.
function test($my_string){
// creating an array by explode()
$my_array=explode(" ", $my_string);
return $my_array; // returning the array
}
// sending a string to function as input //
$collect_array=test("Hello welcome to plus2net");
// displaying the elements of the collected array
foreach ($collect_array as $key => $val) {
echo "$key -> $val <br>";
}
function test($my_array){
foreach ($my_array as $key => $val) {
echo "$key -> $val <br>";
}
}
$collect_array=explode(" ", "Hello welcome to plus2net");
test($collect_array);
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.