Search code examples
phparrayswordpressstrpos

How can I test for a partial string value in an array


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.


Solution

  • 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...