Deepak Kumar Deepak Kumar - 4 months ago 9x
PHP Question

php code to push conditional values in to array

I have variables with values:

$abc = 'Y';

$xyz = 'N';

$pqr = 'Y';

$lmn = 'Y';

I want to create all the variables with value
in to an array, similar to as below:

$result = ( abc, pqr, lmn)


For start, collect all your variables to an array:

$vars = [
  'abc' => $abc,
  'xyz' => $xyz,
  'pqr' => $pqr,
  'lmn' => $lmn

Now you can filter them easy:

$result = array_filter($vars, function($a){return $a == 'Y';});

var_dump(array_keys($result)); // ['abc', 'pqr', 'lmn']