I have some strings which contain , character and I need to explode them into array. For example there are two cases
$str = 'Jack, Rose, John';
Or
$str = 'Jack';
When I used this code to each case
$formatted = str_replace(' ', '', $str); // Remove spaces
$names = explode(',',$formatted); // Split strings to array
In first case, everything goes fine. Three name (Jack, Rose, John) are splitted into array that I can use.
$str = 'Jack, Rose, John';
$formatted = str_replace(' ', '', $str);
$names = explode(',',$formatted);
foreach($names AS $name)
{
// Get user from database using $name.
// Everything works just fine.
}
But in the second case I didn't get an array. When I used foreach it just return empty string for each loop.
$str = 'Jack';
$formatted = str_replace(' ', '', $str);
$names = explode(',',$formatted);
foreach($names AS $name)
{
// Get user from database using $name.
// Return error because $name empty ?!
}
I appreciate your answers to tell me why this happened.
$formatted = str_replace(' ', '', $str);you also remove spaces in the names. So Van Gogh would become VanGogh.