Home > Software engineering >  Array_Map and Strip_Tags expecting string
Array_Map and Strip_Tags expecting string

Time:11-27

PHP Version: 8.1

Hello, I’m trying to implement strip tags on a passed in JSON object that looks like this (just inputting one transaction for brevity):

"{"request":"transactions","id":1,"transactions":[{"date":"2022-11-09","amount":5000,"amount2":2000,"amount3":null,"amount4":null}]}"

I perform json_decode on this object:

 $decoded = json_decode($content_raw, true));

and get the following:

request: "transactions"
id: 1
transactions: array(1)
   0: array(5)
     date: "2022-11-09"
     amount: 5000
     amount2: 2000
     amount3: null
     amount4: null

I then want to strip tags to make sure no one is passing in anything malicious, so I follow the procedure in accordance with php 8.1 in this thread.

PHP: using strip_tags with parameters with array_map

$decoded_clean = array_map(function($v)
    { 
        if (is_null($v)) { //can't pass null into strip_tags starting in php8.1, so have to give a ''
            $v = '';
        }
        return trim(strip_tags($v)); //PROBLEM IS HERE
    }, $decoded['transactions']);
//now that strip_tags is present, replace '' with NULL so the DB will store non-number decimals (i.e., NULL). This is because the database defaults '' to 0.000.
   foreach($decoded_clean as $key=>$array_value) { //key=>value
        if ($array_value=='') { $decoded_clean[$key] = NULL; }
    }

extract($decoded_clean); //this creates a list of variables that are in the array with the name of their key. This makes it easier than having to call $decoded['variable_name'] every time

However, the strip tags function is causing problems and tossing out: “PHP Fatal error: Uncaught TypeError: strip_tags(): Argument #1 ($string) must be of type string, array given in C:\xampp\htdocs\...”

If I make $decoded a string, I then have a problem with array_map expecting an array. What am I doing wrong with my syntax?

Thanks!

CodePudding user response:

What you need is array_walk_recursive with passing argument by reference:

array_walk_recursive($decoded, function(&$v) { 
    if (is_null($v)) {
        $v = '';
    } else {
        $v = trim(strip_tags($v));
    }
});
  •  Tags:  
  • php
  • Related