Sanitize multi dimensional array in php - php

Wrote this function to clean up array and LEAVE 0, null & false as valid values.
function sanitize_array($array = array()) {
if (is_array($array)) {
$filtered_array = array_filter($array, create_function('$a', 'return trim($a)!=="";'));
$filtered_and_trimmed_array = array();
foreach ($filtered_array as $k => $v) {
if (!is_array($v) && !is_object($v)) {
$filtered_and_trimmed_array[$k] = htmlspecialchars(trim($v));
}
if (is_array($v)) {
$filtered_and_trimmed_array[$k] = $this->sanitize_array($v);
}
}
return $filtered_and_trimmed_array;
} else {
return false;
}
}
It's giving me the following error:
g: trim() expects parameter 1 to be string, array given in /home/imgimportsinc/public_html/img_scripts_library/img_functions.php(328) : runtime-created function on line 1
Warning: trim() expects parameter 1 to be string, array given in /home/imgimportsinc/public_html/img_scripts_library/img_functions.php(328) : runtime-created function on line 1

You just need to check that the value to be evaluated is a string before trimming it.
$filtered_array = array_filter($array, function($v) {
return !is_string($v) || (is_string($v) && trim($v) !== "");
});

Related

phpstan not pass over strip_tags

i have string of html which i want to explode by <br>, but sometimes it can be inside of other tags.
if (in_array($param, $customOrdering, true) && $value) {
$ordering = array_search($param, $customOrdering, true);
$segments[$ordering] = [];
if (in_array($param, $explodeParams, true)) {
$values = explode('<br>', $value);
foreach ($values as $v) {
$testing_value = $v;
if (!empty(trim(strip_tags($testing_value)))) {
array_push($segments[$ordering], $this->createSegmentFromParam($param, $v));
138 } elseif (!empty(trim($v)) && $segments[$ordering]) {
139 end($segments[$ordering])->value_raw .= strip_tags($v, $this->allowedTags);
}
}
} else {
array_push($segments[$ordering], $this->createSegmentFromParam($param, $value));
}
}
declaration of createSegmentFormParam
#return ArrayHash
private function createSegmentFromParam($param, $value)
and i have this output from phpStan
138 Right side of && is always false.
139 Cannot access property $value_raw on false.
any ideas how to pass on ? code working well
There is still an open issue for similar behaviour or PHP Stan - False negative with array_push on property
Try not using array_push and replace it on line 138 with the following:
$segments[$ordering][] = $this->createSegmentFromParam($param, $v);
Apart from this in the beginning of your code array_search may return FALSE you do want to check this before going further down the code...

Can not check if the json key value is not present using PHP

I need some help.I need to check weather the key value is present inside the json array or not using PHP but its throwing some warning message and no value is coming. I am explaining my code below.
$mainArr=array(array("type"=>1,"name"=>"hello"),array("type"=>1,"name"=>"hii"));
//echo json_encode($mainArr);
foreach ($mainArr as $v) {
if(!in_array(1, $v['type'])){
$result['primary'][]=array();
}else{
$result['primary'][]=$v;
}
if(!in_array(2, $v['type'])){
$result['secondary'][]=array();
}else{
$result['secondary'][]=$v;
}
}
echo json_encode($result);
Here I need to check if type==2 is not present inside that array it should return blank array but its throwing the below message.
Warning: in_array() expects parameter 2 to be array, integer given in /opt/lampp/htdocs/test/arrchk.php on line 5
Warning: in_array() expects parameter 2 to be array, integer given in /opt/lampp/htdocs/test/arrchk.php on line 10
Warning: in_array() expects parameter 2 to be array, integer given in /opt/lampp/htdocs/test/arrchk.php on line 5
Warning: in_array() expects parameter 2 to be array, integer given in /opt/lampp/htdocs/test/arrchk.php on line 10
{"primary":[[],[]],"secondary":[[],[]]}
Please help me to resolve this issue.
You are using the PHP's in_array function on a scalar value.
$v['type'] is an integer, a simple comparaison like
1 === $v['type']
will do the job
You search element in an array element not an array.
<?php
$mainArr = array(
array(
"type" => 1,
"name" => "hello"
),
array(
"type" => 1,
"name" => "hii"
)
);
//echo json_encode($mainArr);
foreach ($mainArr as $v) {
if (!in_array(1, $v)) {
$result['primary'][] = array();
} else {
$result['primary'][] = $v;
}
if (!in_array(2, $v)) {
$result['secondary'][] = array();
} else {
$result['secondary'][] = $v;
}
}
echo json_encode($result);
?>
$mainArr=array(array("type"=>1,"name"=>"hello"),array("type"=>1,"name"=>"hii"));
//echo json_encode($mainArr);
foreach ($mainArr as $v => $values) {
if(!in_array(1, $values['type'])){
$result['primary'][]=array();
}else{
$result['primary'][]=$values;
}
if(!in_array(2, $values['type'])){
$result['secondary'][]=array();
}else{
$result['secondary'][]=$values;
}
}
echo json_encode($result);
Use array_search() function. For example:
foreach ($mainArr as $v) {
if (!array_search('1', $v)) {
$result['primary'][]=array();
} else {...}

Why these codes show Unsupported operand types and others errors?

I am a beginner.Why following codes show three errors?:
1) Warning: array_keys() expects parameter 1 to be array, integer given in C:\wamp\www\wordpress\wp-content\themes\testtheme\functions.php on line 851
2) Warning: Invalid argument supplied for foreach() in C:\wamp\www\wordpress\wp-content\themes\testtheme\functions.php on line 851
851 line:
foreach (array_keys($team_points + $team_points2) as $key) {
$total_points_final[$key] = (isset($team_points[$key]) ? $team_points[$key] : 0) + (isset($team_points2[$key]) ? $team_points2[$key] : 0);
}
3) Fatal error: Unsupported operand types in C:\wamp\www\wordpress\wp-content\themes\testtheme\functions.php on line 859
859 line:
foreach (array_keys($total_points_final + $team_points3) as $key) {
$total_points_final2[$key] = (isset($total_points_final[$key]) ? $total_points_final[$key] : 0) + (isset($team_points3[$key]) ? $team_points3[$key] : 0);
}
All codes:
$total_points=0;
$team_points;
$team_points2;
$team_points3;
foreach($team_wins as $tw_key=>$tw_val){
$team_points[$tw_key]=$tw_val*3;
}
foreach($team_drawn as $tw_key=>$tw_val){
$team_points2[$tw_key]=$tw_val*1;
}
$total_points_final = array();
$total_points_final2 = array();
foreach (array_keys($team_points + $team_points2) as $key) {
$total_points_final[$key] = (isset($team_points[$key]) ? $team_points[$key] : 0) + (isset($team_points2[$key]) ? $team_points2[$key] : 0);
}
foreach($team_loses as $tw_key=>$tw_val){
$team_points3[$tw_key]=$tw_val*0;
}
foreach (array_keys($total_points_final + $team_points3) as $key) {
$total_points_final2[$key] = (isset($total_points_final[$key]) ? $total_points_final[$key] : 0) + (isset($team_points3[$key]) ? $team_points3[$key] : 0);
}
You can only supply array_keys() a valid array which it inturn returns the keys of the array passed into it as an argument.
It would never except any variable type
You can create a new empty array like this:
$arr = [];
Then add those values to the empty array like this:
$arr[] = $post_id;
$arr[] = $post_total;
Now you can call the new array in your array_keys($arr)
1. array_keys() => The array_keys() function takes only array parameter, you cannot pass integer or string.
example:
$array = array("name"=>"xyz", "email"=>"xxxxxxx#xxxx.xxx");
array_keys($array); //Valid
array_keys(2);//Invalid/Error
2. foreach
foreach is a looping statement, you cannot pass inetger or string to loop it,
pass array to foreach, you cannot pass empty array to foreach,
check empty condition before passing to foreach
example:
foreach($array as $key=>$value) { //valid input for foreach
echo $value;
}

Fatal error when value empty

I have a fatal error claiming that I have a string when I thought I had an array :
Fatal error: [] operator not supported for strings in /Applications/MAMP/htdocs/tankards_wordpress/wp-content/themes/tankardsleague/functions.php on line 566
and also the following warning :
Warning: in_array() expects parameter 2 to be array, string given in /Applications/MAMP/htdocs/tankards_wordpress/wp-content/themes/tankardsleague/functions.php on line 579
I am guessing that I have either a syntax problem somewhere? I thought I had initailized the variables but maybe I missed one? I would appreciate some more experienced eyes having a look.
function forum_subscribe_member_player()
{
global $user_ID;
$players= get_users();
foreach($players as $player)
{
$user_info = get_userdata($player->ID);
$playeremail = $user_info->user_email;
if(!empty($playeremail) && user_can( $player-> ID, 'contributor'))
{
$list = get_option('mf_forum_subscribers_1', array());
if( is_player_subscribed($player->ID)) //remove player if already exists (user clicked unsubscribe)
{
$key = array_search($playeremail, $list);
unset($list[$key]);
}
else
$list[] = $playeremail;
update_option('mf_forum_subscribers_1', $list);
}
}
}
function is_player_subscribed($user_ID)
{
if($user_ID)
{
$useremail = get_userdata($user_ID, 'user_email');
$list = get_option("mf_forum_subscribers_1", array());
if(!empty($list) && in_array($useremail, $list))
{
return true;
}
return false;
}
}
function call_forum_subscribe_member_player()
{
forum_subscribe_member_player();
}
line 566 is $list[] = $playeremail; line 579 is if(!empty($list) && in_array($useremail, $list))
well, you can type-cast the $list to an array to make sure it's always an array even if the initial value is null/empty/etc (basically any type except array):
$list = (array)get_option('mf_forum_subscribers_1', array());

PHP is there a true() function?

I'm writing a function named all to check all elements inside an array $arr, returning a single boolean value (based of $f return value). This is working fine passing custom functions (see the code with $gte0 been passed to all).
However sometimes one want just check that an array contains all true values: all(true, $arr) will not work becase true is passed as boolean (and true is not a function name). Does PHP have a native true() like function?
function all($f, array $arr)
{
return empty($arr) ? false : array_reduce($arr, function($v1, $v2) use ($f) {
return $f($v1) && $f($v2);
}, true);
}
$test = array(1, 6, 2);
$gte0 = function($v) { return $v >= 0; }
var_dump(all($gte0, $test)); // True
$test = array(true, true, false);
$id = function($v) { return $v; } // <-- this is what i would avoid
var_dump(all($id, $test)); // False
all(true, $test); // NOT WORKING because true is passed as boolean
all('true', $test); // NOT WORKING because true is not a function
EDIT: another way could be checking $f in all function:
$f = is_bool($f) ? ($f ? function($v) { return $v; }
: function($v) { return !$v; } ): $f;
After adding this, calling all with true is perfectly fine.
intval might do what you're looking for (especially as the array only contains integers in your example):
var_dump(all('intval', $test)); // False
However, many types to integer conversions are undefined in PHP and with float this will round towards zero, so this might not be what you want.
The more correct "function" would be the opposite of boolean true: empty, but it's not a function, so you can't use it (and invert the return value):
var_dump(!all('empty', $test)); // Does not work!
And there is no function called boolval or similar in PHP, so write it yourself if you need it ;)
Additionally your all function could be optimized. While iterating, if the current result is already FALSE, the end result will always be FALSE. And no need to call $f() n * 2 times anyway:
function all($f, array $arr)
{
$result = (bool) $arr;
foreach($arr as $v) if (!$f($v)) return FALSE;
return $result;
}
Edit: knittl is right pointing to array_filter, it converts to boolean with no function given which seems cool as there is no "boolval" function:
function all($f, array $arr)
{
return ($c = count($arr))
&& ($f ? $arr = array_map($f, $arr) : 1)
&& $c === count(array_filter($arr));
}
var_dump(all(0, $test)); // False
Making the first function parameter optional will do you a proper bool cast on each array element thanks to array_filter.
Better to pass in a function to map the values to booleans that you can then reduce to a final value.
function all($map, $data) {
if (empty($data)) { return false; }
$reduce = function($f, $n) {
return $f && $n;
};
return array_reduce(array_map($map, $data), $reduce, true);
}
$gte0 = function($v) { return $v >= 0; };
$gte2 = function($v) { return $v >= 2; };
$data = array(1, 2, 3, 4, 5);
var_dump(all($gte0, $data));
var_dump(all($gte2, $data));
Then the result of the function remains expectant but the test can be slotted in as needed. You can go a step further and allow both the map and reduce function to be passed in.
function mr($map, $reduce, $data) {
return array_reduce(array_map($map, $data), $reduce, true);
}
You could use PHP's array_filter function, it will remove all 'falsy' values from an array if no callback is specified:
$a = array ( true, true, false );
var_dump($a == array_filter($a));
There isn't any true() function in PHP, you should compare the value to true.
try
return ($f === $v1) && ($f === $v2);
instead of
return $f($v1) && $f($v2);
I think this should work:
function all($f, array $arr)
{
return empty($arr) ? false : array_reduce($arr, function($v1, $v2) use ($f) {
return $f($v1) && $f($v2);
}, true);
}
function isTrue($a)
{
return true === $a;
}
all("isTrue", $test);

Categories