Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display "Not Provided" when variable is null or empty in database

i have a variable array that gets all what my function has retrieved.

$array = $funcs->searchCompany($bizName);

and then i used foreach to check if the value is null for varchar and 0 for int and then i replace its value to "Not Provided" so that everytime it is being called it will say "Not Provided"

foreach ($array as $var) {
            if($var == " " || $var == 0) {
                $var = "Not Provided";
            }
         }

  $name = $var['name'];
            $url = $var['url'];
            $tagline = $var['tagline'];
            $descrip = $var['descrip'];
            $bemail = $var['bemail'];
            $address = $var['address'];
            $city = $var['city'];

but it seems wrong because it destroys the output instead.

like image 856
Kent Abrio Avatar asked Oct 19 '22 02:10

Kent Abrio


2 Answers

You can use & here to pass the value of array to change inside foreach without actually worrying about which is the current array key, which is also sometimes called as passing a variable's value by reference.

Using foreach

foreach ($array as &$value) // note the &
{
    if(empty($value)) $value = 'Not Provided';
    // other values remain untouched
}

Using array_map()

$array = array_map(function($value){
            if(empty($value))
                return 'Not Provided';
            return $value;
        }, $array);

But i will suggest to go with foreach.

like image 145
viral Avatar answered Oct 21 '22 23:10

viral


update your function so something like

foreach ($array as &$var) {
    if($var == " " || $var == 0) {
        $var = "Not Provided";
    }
}

$name = $array['name'];
$url = $array['url'];
$tagline = $array['tagline'];
$descrip = $array['descrip'];
$bemail = $array['bemail'];
$address = $array['address'];
$city = $array['city'];
like image 22
Arpita Avatar answered Oct 22 '22 00:10

Arpita