What is the best approach to extract words from sentences stored in an array and create arrays for each sentence with the contained words in PHP?
To extract words from sentences stored in an array and create arrays for each sentence with the contained words in PHP, you can iterate through the array of sentences, use the `explode()` function to split each sentence into an array of words, and store the result in a new array. Here is a PHP code snippet that demonstrates this approach:
<?php
// Array of sentences
$sentences = [
"This is a sentence.",
"Another sentence here.",
"One more sentence for example."
];
// Array to store arrays of words
$wordArrays = [];
// Iterate through the sentences array
foreach ($sentences as $sentence) {
// Split the sentence into an array of words
$words = explode(" ", $sentence);
// Store the array of words in the wordArrays array
$wordArrays[] = $words;
}
// Print the arrays of words for each sentence
foreach ($wordArrays as $words) {
print_r($words);
}
?>