Illegal Offset of an Array on Production Site - php

I'm getting the following warning message:
Warning: Illegal offset type in
/home/bmtuser/public_html/wp-content/plugins/plugin_name/plugin_file.php
on line 238
The offending line is the following code:
$new_sorted_array[$sort_order] = $term->term_id;
Here is the code before it to set that:
$new_sorted_array = array( );
foreach ( $terms as $term ) {
$taxonomy_id = 'taxonomy_'.$term->term_id;
$sort_order = get_option( $taxonomy_id, $term );
$new_sorted_array[$sort_order] = $term->term_id;
}
ksort( $new_sorted_array, SORT_NUMERIC );
This works fine on my localhost but when I moved it to production it's give me this error. Why would that be the case?

$sort_order cannot be an index of $new_sorted_array. Mostly because it is not a number, neither a string.
Maybe your error displaying is lower on your machine. Include this at the top of your code for maximum error reporting: error_reporting(-1);

The warning means that you're using for index variable of type object. It probably means that always or in some cases $term->term_id is not integer but object.
Firs you have to check the case and in case it is normal situation then you can avoid it by next addition:
<?php
$new_sorted_array = array( );
foreach ( $terms as $term ) {
$xxx=$term->term_id;
if(gettype($xxx)=='object') continue;
$taxonomy_id = 'taxonomy_'.$xxx;
$sort_order = get_option( $taxonomy_id, $term );
$new_sorted_array[$sort_order] = $term->term_id;
}
ksort( $new_sorted_array, SORT_NUMERIC );
?>
In this way you'll avoid bad indexes.
I'm not agree that warning has to be suppressed - they has to be resolved.

Related

PHP 8.1 throws error Uncaught TypeError: Cannot access offset of type string on string [duplicate]

This question already has answers here:
PHP message: PHP Fatal error: Uncaught TypeError: Cannot access offset of type string on string [duplicate]
(5 answers)
Closed last year.
I am checking all my code in readiness for upgrading to PHP 8.1.
The following lines of code work fine in PHP7.4 but throws the above error on the line starting with "$pcount" in PHP 8.1
foreach ($products as $product) {
$pcount[$product['HospitalProductID']] += 1;
}
The $product array looks like this:
(
[HospitalProductID] => 260
[HospitalProtocolID] => 82
)
Any idea why PHP 8.1 does not like this code?
UPDATE
I believe I found the cause of this issue and posting it here un case it might help others in the future.
The error is caused by the use of the += operator in conjunction with an array key that does not yet exist, therefore trying to add 1 to an undefined value.
I changed my code as follows and I no longer get the error.
foreach ($products as $product) {
if (isset($pcount[$product['HospitalProductID']])) {
$pcount[$product['HospitalProductID']] += 1;
} else {
$pcount[$product['HospitalProductID']] = 1;
}
}
PHP 7.4 was just being kind to you in the past. Part of PHP8 is to do away with a lot auto fixing and other nonsense that indulged bad coding and vulnerabilities.
Re write what you have to :
$products = ["HospitalProductID" => 260, "HospitalProtocolID" => 82];
foreach ($products as $product => $id) {
}
$product is your Item and $id is your int.
UPDATE:
Since you have confirmed you are using MYSQLI, you should be using MYSQLI fetch functions like :
fetch_object() Returns your results as an Object.
if ( $products = $mysqli->query( $sql ) ) {
while ( $product = $products->fetch_object() ) {
$product->HospitalProductID;
}
}
$products->close();
fetch_assoc() Returns your results as an Associative Array.
if ( $products = $mysqli->query( $sql ) ) {
while ( $product = $products->fetch_assoc() ) {
$product['HospitalProductID'];
}
}
$products->close();
Here is a list of all possible methods you can use with the result class: https://www.php.net/manual/en/class.mysqli-result.php
I would also implore you to check out Prepared Statements. Especially if you are allowing any type of input from out with the hardcoding of the script: https://www.php.net/manual/en/mysqli-stmt.get-result.php

PHP Warnings: Parameter 2 and Invalid argument supplied foreach()

I am new to code and trying to identify errors on my site. It was created by a company using Php 5.6 and is now running Php 7.3
The debug file has two warnings (I've replaced the specific location with ...):
PHP Warning: Parameter 2 to WPE\Site_Preview::the_posts() expected to
be a reference, value given in ...wp-includes/class-wp-hook.php on
line 288 PHP Warning: Invalid argument supplied for foreach() in
...wp-content/mu-plugins/wpengine-common/plugin.php on line 1021
I've tried looking up the answers here, and the foreach error may be because it's not an array? But I'm not sure what an array is exactly, or how to check for it. Any suggestions and advice would be gratefully received, sorry I'm new to this and teaching myself!
the code for the first error (Parameter 2 expected to be a reference)
// Avoid the array_slice if possible.
if ( $the_['accepted_args'] == 0 ) {
$value = call_user_func( $the_['function'] );
} elseif ( $the_['accepted_args'] >= $num_args ) {
$value = call_user_func_array( $the_['function'], $args );
} else {
$value = call_user_func_array( $the_['function'], array_slice( $args, 0, (int) $the_['accepted_args'] ) );
The code for the second error (invalid argument supplied foreach):
// Some paths might reject CDN completely -- if so, don't do CDN replacements.
// In fact, UNDO any that were done by W3TC!
$undo_cdn = false;
foreach ( $wpe_no_cdn_uris as $re ) {
if ( preg_match( '#' . $re . '#', $uri ) ) {
$cdn_enabled = false;
$undo_cdn = true;
break;

php in_array giving odd result

I've read all the other articles on in_array, and still don't understand why mine is givng odd results. I'm inheriting this code from someone else, and don't fully understand why they did certain things. When a user logs in, data is grabbed from a db, one of the fields being their "level". 1 is an admin, 2 a regular user, etc. Once the data is grabbed from the db, we put the user level (stored as a:1:{i:0;s:1:"2") into an array:
$user_level = unserialize($this->result['user_level']);
$_SESSION['unt']['user_level'] = $user_level;
Later we check to see if this is an admin:
error_log(print_r($_SESSION['abc']['user_level'])); //this is always "1"
if (in_array('1', $_SESSION['abc']['user_level'])) { //should be yes, correct?
Yet somehow the if statement never evaluates as true, even though the SESSION variable is 1. What am I missing?
$_SESSION['abc']['user_level'] doesn't appear to be an array. Looks like you want one of the following.
If gettype($_SESSION['abc']['user_level']) is 'integer':
if ($_SESSION['abc']['user_level']) === 1) {
If gettype($_SESSION['abc']['user_level']) is 'string':
if ($_SESSION['abc']['user_level']) === '1') {
If gettype($_SESSION['abc']['user_level']) is 'string' and its value actually contains the quotes:
if ($_SESSION['abc']['user_level']) === '"1"') {
If it was an array the output would have this structure, not just "1":
Array
(
[0] => 1
)
Even though I noticed closing bracket } missing from your input string I just assumed that you probably might have missed while copy-pasting .
a:1:{i:0;s:1:"2"
So in_array is not the problem but your input string is the problem .With display_errors setting Off you would not see any error when you try to unserialize it .
You could use the below function to check if the input is a valid string to unserialize :
// Copied from http://www.php.net/manual/en/function.unserialize.php
function is_serialized( $str )
{
return( $str == serialize( false ) || #unserialize( $str ) !== false );
}
Then something along these lines :
$inputString = 'a:1:{i:0;s:1:"2";}'; // Is valid and is holding one array of info
// $inputString = 'a:1:{i:0;s:1:"2"'; // Invalid as is missing a closing baracket }
if( ! is_serialized( $inputString ) )
{
echo 'Is not serialized';
}
else
{
$user_level = unserialize( $inputString );
$_SESSION['unt']['user_level'] = $user_level; // Is an array
// Note the second argument as was already pointed by #AsksAnyway
error_log( print_r( $_SESSION['unt']['user_level'] , true ) );
var_dump( in_array( '1' ,$_SESSION['unt']['user_level']) );
var_dump( in_array( '2' ,$_SESSION['unt']['user_level']) );
}

Warning: implode(): Invalid arguments passed in functions.php on line 674

i tried to go online after finishing the website but a error occurs
Warning: implode(): Invalid arguments passed in functions.php on line 674
foreach ( $one_array_font as $font => $variants ) {
$font = str_replace(' ', '+', $font);
$variants = implode(',', array_values($variants['variant']) );
$all_final_fonts[] = $font.':'.$variants;
}
$gfont = implode('|', $all_final_fonts); /* <-- This line fails */
wp_enqueue_style( 'zn_all_g_fonts', '//fonts.googleapis.com/css?family='.$gfont.''.$subset);
if ( $data['zn_main_style'] == 'dark' ) {
wp_enqueue_style('zn-dark-style', get_template_directory_uri() . '/css/dark-theme.css',array() ,false,'all');
}
if ( !empty ( $data['g_fonts_subset'] ) ) {
$subset = '&subset='.str_replace( ' ' , '' , $data['g_fonts_subset']);
}
Not really enough info in the question, but this is what I think is happening:
Firstly, $one_array_font is empty.
This means that the foreach() loop is never run.
This means that the line $all_final_fonts[] = $font.':'.$variants; is never run.
I'm guessing that $all_final_fonts was not defined earlier. Therefore it is still undefined when the code gets to the implode.
The implode() fails because it requires the input field to be an array, but you've given it an undefined variable.
Solution
Ensure that $all_final_fonts is defined regardless, by adding the following line before the foreach() loop:
$all_final_fonts = array();
This will initialise the variable as an array, so that implode() won't complain about it if you don't have any data.
Hope that helps.
You are seeing that warning because $all_final_fonts is not an array.
See http://php.net/manual/en/function.implode.php
regards

Illegal offset in array

I am trying to check array using another loop.
for( $i=0;$i<count($allCheckBoxId);$i++ ) {
if( $allCheckBoxId[$i] != ''){
unset( $contactlist[$cntctnum] );
}
}
I have named $allCheckBoxId, having contactnumber as value. Second array I have named $contactlist having contactnumber as key element.
For particular condition I am retrieving values of first array. Means I would have contactnumber as value retrieve in first array. IF it is not null I am unsetting second element with value contactnumber. but its giving me error on unset( $contactlist[$cntctnum] ); as Illegal offset type in unset in
Here comes interesting part.
You know, programming is not just writing the code.
Most of time programming is looking for errors. Not by asking questions on stackoverflow, but by amending your code and studying it's output and error messages. Some sort of investigation.
If you have got such an error message, doesn't that mean that somewhing wrong with offset type? Why not to print the problem variable out? just print it out:
for( $i=0;$i<count($allCheckBoxId);$i++ ) {
var_dump($cntctnum);
var_dump($allCheckBoxId[$i]);
var_dump($contactlist[$cntctnum]);
if( $allCheckBoxId[$i] != ''){
unset( $contactlist[$cntctnum] );
}
}
and see what's particularly wrong with your offset
Try casting your key into a string. Replace:
$contactlist[$cntctnum]
With
$contactlist[(string) $cntctnum]
OR
for($i = 0; $i < count($allCheckBoxId); $i++) {
if($allCheckBoxId[$i] != '') {
$key = (string) $cntctnum;
unset( $contactlist[$key] );
}
}
PHP associative arrays, as of PHP 5.4 will issue a PHP Warning: Illegal Offset Type if you use something other than a string as a key.
Furthermore, if this doesn't help, head over to the PHP Array Manual and do a Ctrl/Cmd + F for "Illegal Offset Type."

Categories