In the code below, the idea is to update the $values array by the $value assigned reference variable.

<?php

$str = 'value one, values, ';

$values = explode(',', $str));

print_r($values);

foreach($values as &$value)
{
	if(!empty(trim($value))
	{
		$value = trim($value);
	}
	else unset($value);
}

print_r($values);

?>

What am I missing - because this does not work!

    Read the PHP manual on [man]unset/man: "If a variable that is PASSED BY REFERENCE is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called."

    This applies here, so what you should do is:

    <?php
    
    $str = 'value one, values, ';
    
    $values = explode(',', $str);
    
    print_r($values);
    
    foreach($values as $key => &$value)
    {
        $value = trim($value);
        if(empty($value))
        {
            unset($values[$key]);
        }
    }
    
    print_r($values);
    
    ?>

      Or in this case

      $values = array_filter(array_map('trim', $values));
      

        This is what I was trying to achieve:

        function name_case($string)
        {
        	$values = explode(" ", $string);
        
        $values = array_filter(array_map('trim', $values));
        
        foreach($values as $key => $value)
        {
        	if(strlen($value) > 3 && ctype_alpha($value))
        	{
        		$values[$key] = ucwords(strtolower($value));
        	}
        	else $values[$key] = strtoupper($value);
        }
        
        return implode(" ", $values);
        }

        This:

        print_r(name_case("akg VMS 2321k raDio MiCroPhone "));
        

        Gives us:

        AKG VMS 2321K Radio Microphone
        

        and this:

        print_r(name_case(" shure sm 58 radio microphone & shure vms-221 receiver "));
        

        gives us:

        Shure SM 58 Radio Microphone & Shure VMS-221 Receiver
        

        Makes for a more visually pleasing product title.

          Write a Reply...