1

I have an array like this:

Array ( [PlasticContainmentTrained] => 0 [AvoidDustSpreadTrained] => 1 [PostRenCleaningTrained] => 0 [EntranceWarningSign] => 1 [IntObjectCovered] => 1 [IntHVAC] => 0 [IntWindowClosed] => 1 [ExtWindowClosed] => 0 [IntDoorClosed] => 1 [ExtDoorClosed] => 0 [DoorCovered] => 1 [IntFloorCovered] => 0 [ExtGroundCovered] => 1 [ExtVertContainment] => 0 [WasteContained] => 1 [AllChipsDebris] => 0 [WorkAreaSurface] => 0 [DustClearanceTesting] => 1 [WasteHandlingTrained] => 1 [MaintainContainmentTrained] => 0 [PostingWarningSignTrained] => 1 [DescriptionOfRenovation] => bnfdbndljnbljdfnbljkdnfljn [TrainedWorkers] => jvndfjnvdfvjndfljvndfljvn [DustSamplingTechnicanNames] => jvnfjdfnlvjdfjvndfljndflj [QualificationCopies] => dfjvdjf [KitUsed] => vjnjkdsfnvljdnvdjfvndfjbnjgbnndfn [TestLocations] => jdfjnvljndfvjdnfvjdnfvjkfnlj [CertifiedRenPerformed] => fdjndfljvndfljvndfjvndflk [ReportAttachPath] => undefined [IAccept] => undefined [ProjectId] => 1 ) 

and i want to filter this array but only 'undefined' values not '0'. i have used array_filter() function for this:

function filterValue($var)
        {

            if($var=='0')
            {
                return 0;
            }
            elseif($var!='undefined')
            {
                return $var;
            }
        }
        $this->data = array_filter($_POST, "filterValue");

but it also filters '0' values. how can i do this.

Please any body help me...

2 Answers 2

1

That's because '0' evaluates to boolean false. Just check for undefined, and return false if it is undefined, true if it isn't:

<?php
$data = array_filter( $data, function( $element ) {
  return $element !== 'undefined';
});
Sign up to request clarification or add additional context in comments.

Comments

0

You could also create a callback function to reuse like your original example, which helps cut down on repeated code. This custom callback function also trims spaces, and allows you to specify an array of values you don't want filtered out:

// Customized "array_filter" callback to preserve "0" in submitted values:
function empty_array_filter($val) {
    $val = trim($val);
    $allowed_vals = array('0'); // List of values to keep (e.g. these should not be treated as "false").
    return in_array($val, $allowed_vals, true) ? true : ( $val ? true : false );
}

Then use your array filter with your custom callback like so:

// Use the custom callback instead of the default one:
$array_data = array_filter($array_data, 'empty_array_filter');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.