2

So I have a checkbox form that stores values in an array, with several values for each key. How can I test if a value is checked? in_array() isn't returning true for values that are in the array.

print_r($array) results:

Array ( [auto_loans] => auto_36_new,auto_48_new,auto_60_new,auto_72_new [mortgage_rates] => 30_year_fixed,15_year_fixed,7_1_arm_30_year,7_1_arm_15_year,5_1_arm_30_year,5_1_arm_15year,3_1_arm_30_year )

Basically, if any checkbox is true I want to output its corresponding rate.

if (in_array("auto_36_new", $array))
  {
  // print the 36 month auto loan rate
  }
elseif (in_array("auto_48_new", $array))
  {
  // print the 48 month auto loan rate
  }
//etc... 

I can't get any code to return positive for any loan rate ID, even though it's in the array printout. What am I doing wrong? I'm not even sure if in_array is the most efficient way to handle this, so I'm not tied to that. ideally I want to limit the query to a certain number of results due to front-end constraints, but first I need to get form results.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
jbro
  • 25
  • 4

2 Answers2

0

not sure how actually your front-ent collects the form values, but it looks like on back-end you get checked values joined with comma...

try this

$autoLoans = explode(',', $array['auto_loans']);
if (in_array('auto_36_new', $autoLoans)) {
  //...
}
zoryamba
  • 196
  • 11
  • missing a pesky semicolon after line 1, but otherwise works, thanks! – jbro May 06 '19 at 21:23
  • fixed, sorry. you might also have to check, if 'auto_loans' key exists in form data. something like `$autoLoans = isset($array['auto_loans']) ? explode(',', $array['auto_loans']) : [];` Otherwise you could get notice-level error Undefined offset if your form data has no such key. – zoryamba May 06 '19 at 21:26
0

Another way to do this would be to use strpos on the specific array element. An example:

<?php

$arr = [
    'auto_loans' => 'auto_36_new,auto_48_new,auto_60_new,auto_72_new',
    'mortgage_rates' => '30_year_fixed,15_year_fixed,7_1_arm_30_year,7_1_arm_15_year,5_1_arm_30_year,5_1_arm_15year,3_1_arm_30_year',
];

if (strpos($arr['auto_loans'], 'auto_36_new') !== false) {
    // print the 36 month auto loan rate
} elseif (strpos($arr['auto_loans'], 'auto_48_new') !== false) {
    // print the 48 month auto loan rate
}
// etc...
  • that works! I tried strpos() but not on the specific element. Thanks! if/else isn't the best for my case, I may need to use switch, but this is a big help. – jbro May 06 '19 at 21:19
  • strpos is not the best choice here... could cause collisions for values `15_year_fixed` and `5_year_fixed` for example... – zoryamba May 09 '19 at 17:46