0

I'm trying to replace quotes and others characters from a mysql result array, using strtr() function. But i got Warning: strtr() expects parameter 1 to be string, array given and null values.

Heres my code:

  while($rows = mysqli_fetch_assoc($list)){

    $string_filter = array(';'=>'','['=>'',']'=>'','{'=>'','}'=>'','"'=>'',"'"=>'');

    $data[$rows['id']] = strtr($rows,$string_filter);

  }

$data is an array that i want to remove/trim the characters specified in $string_filter array. Heres the content sample from $data:

Array ( [1] => Array ( [id] => 1 [user_id] => 204554 [name] => Rich [group] => PL [ai] => BA [image] => 204554-35849.jpg ) [2] => Array ( [id] => 2 [user_id] => 124534 [name] => James [group] => SS [ai] => IT [image] => 123141-12312.jpg )...
4
  • Replace them with what? strstr() searches strings, I suspect you're looking for str_replace(). Commented Jan 17, 2022 at 23:17
  • In fact i want to remove this characters. Commented Jan 17, 2022 at 23:21
  • For the specified row? Or for $rows? Your code is confusing, for instance what is $data, and what do you expect your code to return? Commented Jan 17, 2022 at 23:22
  • For every row value inside the loop. $data is an array. I want my code to return an array with specified characters in $string_filter removed. Commented Jan 17, 2022 at 23:31

1 Answer 1

1

Quick Question, are you sure these characters actually exist in your data? Because the characters you are trying to remove are the ones php will automatically append to an array when that array is viewed via the print_r function. To be precise this statement

print_r(array('key' => 'value'));

will output

Array([key] => value)

even tough there is no actual [ or ] present in the arrays data itself.

In any case this code snippet will clean the keys and values of your array:

$string_filter = array(';'=>'','['=>'',']'=>'','{'=>'','}'=>'','"'=>'',"'"=>'');
while($rows = mysqli_fetch_assoc($list)){    
    $cleanedrow = [];
    foreach($rows as $key => $value) {
        $cleanedrow[strtr($key, $string_filter)] = strtr($value, $string_filter);
    }
    $data[$rows['id']] = $cleanedrow;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, chars like single quotes do exist in data...But your script solve the problem. Thanks =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.