how to use the unset in ternary operator using php

1.2k Views Asked by At

I want to unset the value for certain condition . if i'm use unset keyword it through an error.please any one help me in this case.

$reportHeader = array("name" =>  !empty($name) ? "Name" : "0", 
    "number" => !empty($number) ? "Number" : "0");

In this case i print the Name and number is present if not present i return 0.but i no need to print 0.if condition fails i need to unset the value. I tried like this:

 $reportHeader = array("name" =>  !empty($name) ? "Name" : unset(), 
        "number" => !empty($number) ? "Number" : unset();

But it through an error

3

There are 3 best solutions below

2
drmonkeyninja On

You can't use unset() like that, it expects a variable to be passed to it to unset (see the PHP documentation. Instead populate your array with null values where the value hasn't been set and then use array_filter to remove the indexes you don't want.

$reportHeader = array(
    "name" =>  !empty($name) ? "Name" : null,
    "number" => !empty($number) ? "Number" : null
);
// Now remove the 'unset' values
$reportHeader = array_filter($reportHeader);
0
Qirel On

unset() needs one or more arguments. So if you enabled error-reporting, and checked the documentation for this function, you would see this yourself. Then the question is, what exactly are you trying to unset?

You need to return something as the value of your array, not have unset() become the value (like you currently are trying). If you intend only to add the element if the value is not empty, you can do

$reportHeader = array();
!empty($name) ? $reportHeader['name'] = "Name" : null;
!empty($number) ? $reportHeader['number'] = "Number" : null;

This adds only values to your array if they are not empty.

Although, a standard if does this quite clean, too - just because something can be written as a ternary operator, doesn't mean it should.

if (!empty($name))
    $reportHeader['name'] = "Name";
0
PHP Geek On

You can simply use folowing code

!empty($name) ? $reportHeader["name"] = "Name" : "";
!empty($number) ? $reportHeader["number"] = "Number" : "";