What would be the best way to create a dynamic array with explode?

ICHaps

New member
Hello.

I'm about to build a very basic search routine. I'd like to search for 1 or more words in a database, then display the Title and Description, that's my idea.


So I'd just like to check the best way to split words into a dynamic array please. At present I've got a very rough and basic coding routine:-

<?php
//Search for selected word(s)
$search = $_POST["txtsearch"];
echo $search."<br>";

$wordsearch = explode(" ", $search);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

/*
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
*/
?>

I'd just like to ask,

As I don't know how many words $_POST["txtsearch"] will have.
What would be the best way to create a dynamic array with explode?

I was thinking of:-

<?php
$i=0;
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
while {
echo $pieces[$i]; // piece1
i++;
if ($pieces[$i] == "") { exit; }
}
?>

Then connect to the database.

Any suggestions, would be welcome.
Thank You.
 
Hi,
To know the size of the array you can easly use sizeof or count function:
PHP:
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(' ', $pizza);
$size = sizeof($pieces);
echo 'List of ' . $size . ' element(s):<br>';
for ($i=0; $i<$size; $i++) {
    echo '$piece[' . $i . '] = ' . $pieces[$i] . '<br>';
}
More useful array related functions you can find there: https://www.w3schools.com/php/php_arrays_functions.asp
 
Back
Top