Need better simpler solution for conditional link

Viewed 61

I have three condition/variable combination e.g. below called amounts:

$a = 15000; $b = 10000; $c = 5000;
or
$a = 10000; $b = 15000; $c = 0;
or
$a = 12000; $b = 0; $c = 15000;
etc. 

At least each $a or $b or $c above is not 0 (zero).

If the amount of each not 0 (zero) it have its own associated array e.g. if $b == 0 then $b_array will not set/created, assume all is not 0(zero) then below arrays are created:

$a_array = array('id'=>1);
$b_array = array('id'=>2);
$c_array = array('id'=>3);

If $a / $b / $c is not 0 (zero) then if $b or $c not zero it needs to be linked to $a or $b (if not zero) as below:

if($a != 0 && $b != 0 && $c != 0){
    $b_array['id_link'] = $a_array['id'];
    $c_array['id_link'] = $a_array['id'];
} elseif ($a != 0 && $b != 0 && $c == 0){
    $b_array['id_link'] = $a_array['id'];
} elseif ($a != 0 && $b == 0 && $c != 0){
    $c_array['id_link'] = $a_array['id'];
} elseif ($a == 0 && $b != 0 && $c != 0){
    $c_array['id_link'] = $b_array['id'];
}

The result for conditional statement above seems correct as you can check at the php sandbox

Is there any better idea for the conditional code and is there a missing condition (error handling). Any idea or solutions is greatly appreciated. Thanks!!

1 Answers

If I understand your question correctly, instead of checking for every combination possible, just get the first non zero number and assign it's id as id_link to all of them like below:

<?php

$id_link = -1;

if($a !== 0){
    $id_link = $a_array['id'];
}else if($b !== 0){
    $id_link = $b_array['id'];
}else if($c !== 0){
    $id_link = $c_array['id'];
}


$a_array['id_link'] = ($b_array['id_link'] = ($c_array['id_link'] = $id_link));

Online Demo

(The brackets in the expression are added just for readability since they are redundant in case of PHP)


Update:

If you wish to leave the array with it's corresponding variable without the id_link key, then you can just use another 3 if conditions to take care of it.

<?php

$id_link = -1;

if($a !== 0){
    $id_link = $a_array['id'];
}else if($b !== 0){
    $id_link = $b_array['id'];
}else if($c !== 0){
    $id_link = $c_array['id'];
}

if($a !== 0){
   $a_array['id_link'] = $id_link;
}

if($b !== 0){
   $b_array['id_link'] = $id_link;
}

if($c !== 0){
    $c_array['id_link'] = $id_link;
}

Online Demo

Related