Refactor array_key_exists in PHP8 - php

Having just attempted to upgrade from PHP 7.4.33 to 8.0.27 I have encountered the following error on a key page:
Got error 'PHP message: PHP Warning: Undefined array key 1981 in
drivers_standing_table.php on line 56
PHP message: PHP Fatal error: Uncaught TypeError: array_key_exists():
Argument #2 ($array) must be of type array, null given in
drivers_standing_table.php:56
1981 is an id (int) associated with a record in the database. For example, in this case a competitor has an id of 1981.
Line 56 of drivers_standing_table.php (and slightly thereafter) looks like this:
// LINE 56:
if (array_key_exists($round, $shared_drivers[$driver_id])) {
$lender_id = $shared_drivers[$driver_id][$round];
$lender_race_result = $drivers_race_result_array[$lender_id][$round][0];
$cls_name = $drivers_race_result_array[$lender_id][$round][1];
$race_result = $drivers_race_result_array[$driver_id][$round][0];
if (array_key_exists($round, $drivers_race_result_array[$driver_id])) { ?>
<td align='center' style="background: orangered;">
<?php echo $race_result . '/' . $lender_race_result; ?>
</td>
<?php
$exit_flag = true;
$i++;
} else {
?>
<td align='center' class='<?php echo $cls_name; ?>'>
<?php echo $lender_race_result; ?>
</td>
<?php }
}
The error is preventing the script from continuing to run, breaking the page.
How should I refactor line 56 to work with PHP8?

You can use isset() instead, as it won't throw an error at any nesting level:
if (isset($shared_drivers[$driver_id][$round])) {
Keep in mind that isset() will return false if the value is null though, but I don't think it's a concern in your case.

array_key_exists expect second parameter to be an array you are passing null
First solution is to check if the second parameter is an array you can do that with is_array like that :
if (isset($shared_drivers[$driver_id])
&& is_array($shared_drivers[$driver_id])
&& array_key_exists($round, $shared_drivers[$driver_id])) {
Or you can use Null Coalescing Operator to change that null with empty array
if (array_key_exists($round, $shared_drivers[$driver_id]??[])) {

You can check that the outer array key exists first and that this value is an array, stepping into the array levels through the if statement:
if ( is_array($shared_drivers)
&& array_key_exists($driver_id, $shared_drivers)
&& is_array($shared_drivers[$driver_id])
&& array_key_exists($round, $shared_drivers[$driver_id]) ){
This means that if the $shared_drivers[$driver_id] doesn't exist or is not an array the IF statement will abort before testing an invalid array reference ( $shared_drivers[$driver_id]) .
If you're certain that $shared_drivers is an array and exist at this point, you can streamline the above code by removing the first argument.

Related

i am getting this error although its working but its gives warning

Warning: Trying to access array offset on value of type null in
C:\xampp\htdocs\ecommerce_cms_tutorial\register.php on line 172
}elseif ($row_register['email'] != $email && $password == $confirm_password) {
You are dealing with a null array element:
You have 2 options:
Use isset($arr['element'))
Use # with array like #$arr['element'];
if(isset($row_register['email']){
// Enter your code here
}
This happens because $row_register is not null but the index 'email' does not exist (yet). because you are using newer version of PHP You will need to add the following:
isset($row_register['email'])

PHP - Undefined index solving returns warining

I have a function within my PHP project which has some specific params..
$user_sequence = $user['user_sequence'];
if ($cached || !$user_sequence) {
return;
}
Notice: Undefined index: user_sequence
I have fixed that with:
if (isset($user['user_sequence'])) {
$user_sequence = $user['user_sequence'];
}
But now my second if() clause get's a warning:
Variable '$user_sequence' is probably undefined
Would setting it to null before if() be the best approach to solve it? Thanks
Spelled out in full, you need to specify what the value should be if $user['user_sequence'] is not set. In your second if statement, you are checking !$user_sequence, so a logical default value would be boolean false:
if (isset($user['user_sequence'])) {
$user_sequence = $user['user_sequence'];
}
else {
$user_sequence = false;
}
Luckily, PHP doesn't make use write out that whole if statement, because we can use the null coalescing operator, and shorten it to this:
$user_sequence = $user['user_sequence'] ?? false;
In other situations, you might want to default to an empty array ($something ?? []) or even just null ($something ?? null).

Warning: array_key_exists() expects parameter 2 to be array, boolean given. Wordpress

I'm new in php and having problem with a piece of my code if the key given exist. The code of error are below and i don't have a idea what is causing it. Please help.
"Warning: array_key_exists() expects parameter 2 to be array, boolean given in"
The line
if ( is_array(array_key_exists('sizes',wp_get_attachment_metadata($attach_id)) == false ){}
As ArSeN already pointed out, is_array(array_key_exists( doesn't make much sense. I guess you were trying: a) is not array or b) lacks a specific key.
Using a temporary variable you can do something like
if ( !is_array($meta=wp_get_attachment_metadata($attach_id)) || !array_key_exists('sizes', $meta) ) {
// ....
}
Or, in case you try to access the meta data more often (or simply as a coding style):
$meta=wp_get_attachment_metadata($attach_id);
if ( !is_array($meta) || !array_key_exists('sizes', $meta) ) {
// ....
}
You could drop a ternary into that thing to uglify the hell out of it.
if ( is_array(array_key_exists('sizes',wp_get_attachment_metadata($attach_id)) == false) ?: array() ){}
This way if the attachment metadata does not exist, it will provide an empty array, which in turn will produce a false from array_key_exists, which is similar to the behave of the desired code.

Skip a PHP Variable (that is itself an Array) when Cycling through an Array with "foreach"

Update: It appears, upon further experimentation, that the problem is with $val. It may have been more helpful at describing the problem had I copied the full text of the error message: "Catchable fatal error: Object of class mysqli_result could not be converted to string in ...". Evidently, PHP (for some reason) can't convert $val to a string. Note that the error message states that it is a catchable error. I had hoped that the use of the "continue" parameter would bypass this error.
The code below works provided that none of the variables are themselves an array.
foreach ($_SESSION as $key=>$val)
{echo $key. ": ".$val. "<br>";}
Through experimentation, I figured out which "$key" was itself an array. Since I figured out which variable was causing the problem, the easy solution was simply to unset it. But that is not a good solution.
unset($_SESSION['issuenum_index']);
To get around the error, I attempted to use the "continue" statement. It did not work. See the code below.
foreach ($_SESSION as $key=>$val)
{if(is_array($key)) continue;
{echo $key. ": ".$val. "<br>";}}
How can the code above be revised to skip a variable when it is an array without triggering an error message?
Update continued: The "foreach" code failed and generated the following messages when the iteration reached the $key index "issuenum_index". Note that this "foreach" code correctly identifies the "$key" index as "issuenum_index" but hangs at this part of the code: "var_dump($val);"
foreach ($_SESSION as $key=>$val)
{ var_dump($key);
var_dump($val);
echo "<br>";
}
"Warning: var_dump(): Couldn't fetch mysqli_result in ..."
*Warning: var_dump(): Property access is not allowed yet in /var/www/sfmags/testform.inc.php on line 60
object(mysqli_result)#1 (5) { ["current_field"]=> NULL ["field_count"]=> NULL ["lengths"]=> NULL ["num_rows"]=> NULL ["type"]=> NULL } *
I have a solution that answers the question as posted. Essentially the variable $val associated with ($_SESSION['issuenum_index']) is an OBJECT.
In reading up on this, I found the following code snippet, that I applied to my case.
foreach ($_SESSION as $value) {
echo gettype($value), "\n";
}
The result: "integer string object integer integer integer integer". Which disclosed that one of my elements was an "object". The third element is the variable: $_SESSION['issuenum_index'].
I revised the original code to add "not object".
foreach ($_SESSION as $key=>$val)
if(!is_object($val))
{
echo $key. ": ".$val. "<br>";
} else {
echo "$key is an object <br>";
}
The code worked. I also revised the code to identify (echo) that "$_SESSION['issuenum_index']" was an object. This revision provides me a list of all my $_Session variables. My understanding of how this all goes together is still incomplete. I don't know why it works with $val? But that is another question.
$key, at one point in cycling through "$_SESSION" stands for "issuenum_index"
$val, I believed represented a value, such as "1". However, it is reported as being an "object". While this question is solved, I will still need to learn more.

error on form submit if no second parameter

When i submit my form and if the second parameter is empty.
It throws error.
Message: in_array() expects parameter 2 to be array, null given
Filename: user/Users_groups.php Line Number: 250
I know there is no second parameter. $this->session->userdata('modify')
if (!in_array('user/users_groups', $this->session->userdata('modify'))) {
$this->error['warning'] = 'You do not have permission to modify';
}
Is there away to make it stop throwing that error when user or I try to submit form if no second parameter $this->session->userdata('modify')
But still have that code.
Try to check first if parameters are valid:
<?php
if(is_array($this->session->userdata('modify')) && !empty($this->session->userdata('modify')))
{
if (!in_array('user/users_groups', $this->session->userdata('modify')))
{
$this->error['warning'] = 'You do not have permission to modify';
}
}else{/* handle errors */}
?>
Replace the null value with an empty array before the if statement:
Could use a ternary operator like this:
$array = (is_array($this->session->userdata('modify')))
? $this->session->userdata('modify')
: Array()
It will use the 'modify' array if it's an array, else will pass an empty array
I would also check array_search() function because it can be compared with NULL wich is returned if irregular parameters set.
5.3.0 As with all internal PHP functions as of 5.3.0, array_search() returns NULL if invalid parameters are passed to it.

Categories