Thursday 30 August 2018

php arrays: search for corresponding values ​​in a table and replace them with array keys

Please i want to loop through my table and compare values with an array in a php included file. If there is a match, return the array key of the matched item and replace it with the value of the table. I need help in returning the array keys from the include file and comparing it with the table values.

    $myarray = array(
    "12aaa"=>"hammer",
    "22bbb"=>"pinchbar",
    "33ccr"=>"wood" );

in my loop in a seperate file
      include 'myarray.inc.php';
      while($row = $db->fetchAssoc()){
      foreach($row as $key => $val)
         if $val has a match in myarray.inc.php
          {
             $val = str_replace($val,my_array_key);
          }

   }

So in essence, if my db table has hammer and wood, $val will produce 12aaa and 3ccr in the loop. Any help? Thanks a lot

You are looking for array_search which will return the key associated with a given value, if it exists.
$result = array_search( $val, $myarray );
if ($result !== false) {
  $val = $result;
}

0 comments:

Post a Comment