Deepak Kumar Deepak Kumar - 1 year ago 80
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)

Answer Source

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']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download