Arif Hossin Arif Hossin - 2 months ago 7
PHP Question

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);
}

Answer

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)