- PHP Lesson 6 Array(Warning: Undefined array key)
- >Solution :
- [Solved] Warning: Undefined array key
- Solution 1: Use isset
- Solution 2: Use Ternary Operator
- Solution 3: Check For Null Value
- Frequently Asked Questions
- Summary
- Php: Fastest Way to Handle Undefined Array Key
- Old answer
- Beginner php Warning: Undefined array key
- Why it shows Undefined array key title error?
- Is there an idiomatic way to get a potentially undefined key from an array in PHP?
- PHP: Solve undefined key / offset / property warnings. Multi-level nested keys
- Solution 1 – isset function
- Solution 2 – property_exists / array_key_exists functions
- Solution 3 – ?? coalesce operator (>=PHP 7)
- Solution 4 – disable warnings
- Solution 5 – custom function
PHP Lesson 6 Array(Warning: Undefined array key)
recently I started to teach myself php with the book Php & mysql by (Jochen Franke & Axel Borntrager).
Now I’m at lesson 6 Working with arrays: but after taking over the script I get the following Error:
Warning: Undefined array key 6 in C:\xampp\htdocs\Les – 6 Array 2.php on line 15.
It gives the values correctly. but always followed by the error Warning: Undefined array key. What strikes me is that this is always at the beginning of the while code.
I just don’t understand where I’m making the mistake. can someone explain to me where i am making the mistake.
Array unsorted
"; echo "assortment :"; $i=0; while($assortment[$i]) < echo $assortment[$i] . " "; $i++; >echo "
Number:"; $i=0; while($number[$i]) < echo $number[$i] . " "; $i++; >echo "
"; ?>
>Solution :
When $i gets to 6, you want that condition to be false; it is, but in order to discover that, PHP tries to look at the value of $assortment[6] , and complains that there’s no such element in the array.
To avoid this, you could use the special isset pseudofunction:
(This will also end on null elements, so if you wanted to include those in a loop you’d need array_key_exists instead.)
However, a more elegant way to write the loop exists in PHP: the foreach loop:
foreach($assortment as $item)
[Solved] Warning: Undefined array key
To solve Warning: Undefined array key in PHP You just need to check that what you are trying to get value exists or Not So you have to use isset. Just like this. Now, Your error must be solved. Let’s explore the solution in detail.
Solution 1: Use isset
You just need to check that what you are trying to get value exists or Not So you have to use isset. Just like this. Now, Your error must be solved.
Solution 2: Use Ternary Operator
You can also Use Ternary Operator as a Conditional Statement. Ternary Operator syntax is (Condition) ? (Statement1) : (Statement2); We can use Just Like this.
And now Your error must be solved.
Solution 3: Check For Null Value
Usually, This error occurs Cause Of a Null Or Empty Value So You need to use a Conditional Statement here. You can achieve this Just like the given below.
We can Also Use Multiple Conditions Cause the Value should be Null Or Empty So We are Going to use both Conditions in our IF.
And now, Your error will be solved.
Frequently Asked Questions
How To Solve Warning: Undefined array key Error ?
To Solve Warning: Undefined array key Error You can also Use Ternary Operator as a Conditional Statement. Ternary Operator syntax is (Condition) ? (Statement1) : (Statement2); And now Your error must be solved.
Warning: Undefined array key
To Solve Warning: Undefined array key Error You Just need to check that what you are trying to get value is exists or Not So you have to use isset. Just like this. Now, Your error must be solved.
Summary
The solution is quite simple you need to check for null or empty values before using any variable. You can use isset(), if-else or ternary operator to check null or empty values. Hope this article helps you to solve your issue. Thanks.
Php: Fastest Way to Handle Undefined Array Key
Since PHP 7 you can accomplish this with the null coalesce operator:
Old answer
First of all, arrays are not implemented as a B-tree, it’s a hash table; an array of buckets (indexed via a hash function), each with a linked list of actual values (in case of hash collisions). This means that lookup times depend on how well the hash function has «spread» the values across the buckets, i.e. the number of hash collisions is an important factor.
Technically, this statement is the most correct:
return array_key_exists($key, $table) ? $table[$key] : null;
This introduces a function call and is therefore much slower than the optimized isset() . How much? ~2e3 times slower.
Next up is using a reference to avoid the second lookup:
$tmp = &$lookup_table[$key];
return isset($tmp) ? $tmp : null;
Unfortunately, this modifies the original $lookup_table array if the item does not exist, because references are always made valid by PHP.
That leaves the following method, which is much like your own:
return isset($lookup_table[$key]) ? $lookup_table[$key] : null;
Besides not having the side effect of references, it’s also faster in runtime, even when performing the lookup twice.
You could look into dividing your arrays into smaller pieces as one way to mitigate long lookup times.
Beginner php Warning: Undefined array key
I’ll assume you want to know how to get rid of this error message.
The first time you load this page you display a form and $_GET is empty (that’s why it is triggering warnings). Then you submit the form and the fname and age parameters will be added to the url (because your form’s method is ‘get’).
To resolve your issue you could wrap the two lines inside some if-statement, for example:
Your name is
Your age is
Why it shows Undefined array key title error?
I see you just missed one level in comment object:
[
'name' => "post_comments",
'data' => [
'comments' =>
collect($post['comments'])->map(function ($comment) return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],
];
>),
]
],
Is there an idiomatic way to get a potentially undefined key from an array in PHP?
More elegant way of doing it:
$value = ifsetor($arr[$key]);
$message = ifsetor($_POST['message'], 'No message posted');
etc. Here $value is passed by reference, so it wouldn’t throw a Notice.
- NikiC’s blog — The case against the ifsetor function
- PHP RFC — https://wiki.php.net/rfc/ifsetor
PHP: Solve undefined key / offset / property warnings. Multi-level nested keys
Sometimes we may want to return null or empty string for non-existing multi-level/nested keys or properties in PHP instead of warnings. Also it would be convenient to use bracket ([]) and arrow (->) operators for array keys / object properties interchangeably.
First let’s initialize some variables in below PHP code block:
class Foo {
public $prop1 = ‘prop1_val’ ;
public $prop2 = [ ‘key’ => ‘val’ ] ;
public $prop3 = [ ] ;
}
$cls = new Foo ( ) ;
$cls -> prop3 = [ ‘cls’ => new Foo ( ) ] ;
$arr1 = [ ‘key1’ => ‘val1’ ] ;
Now let’s execute the following:
echo $arr1 [ ‘key1’ ] . ‘
‘ ;
echo $cls -> prop1 . ‘
‘ ;
echo $cls -> prop2 [ ‘key’ ] . ‘
‘ ;
echo $cls -> prop3 [ ‘cls’ ] -> prop2 [ ‘key’ ] . ‘
‘ ;
The output of the above code will be (no errors or warnings, all clean):
echo $arr1 [ ‘key2’ ] . ‘
‘ ; // non existent array key
echo $cls -> prop4 . ‘
‘ ; // non existent object property
echo $cls [ ‘prop3’ ] [ ‘cls’ ] -> prop2 [ ‘key’ ] . ‘
‘ ; // call object property using [] operator
Warning: Undefined array key «key2» in.
Warning: Undefined property: Foo::$prop4 in.
Fatal error: Uncaught Error: Cannot use object of type Foo as array in.
Solution 1 – isset function
We can use PHP’s isset($var) function to check if variable is set before using it. This will solve undefined key and undefined property issues.
echo ( isset ( $arr1 [ ‘key2’ ] ) ? $arr1 [ ‘key2’ ] : ‘def_val’ ) . ‘
‘ ;
echo ( isset ( $arr1 [ ‘k1’ ] [ ‘k2’ ] ) ? $arr1 [ ‘k1’ ] [ ‘k2’ ] : ‘def_val’ ) . ‘
‘ ; // nesting array keys also works
echo ( isset ( $cls -> prop4 ) ? $cls -> prop4 : ‘def_val’ ) . ‘
‘ ;
echo isset ( $cls [ ‘prop3’ ] [ ‘cls’ ] -> prop2 [ ‘key’ ] ) ? $cls [ ‘prop3’ ] [ ‘cls’ ] -> prop2 [ ‘key’ ] : ‘def_val’ ;
This solution fixes only undefined key/property issue, but Cannot use object of type Foo as array error still remains. Also we need to call the same key twice which may be problematic for very large arrays.
Solution 2 – property_exists / array_key_exists functions
Similar to Solution1 we can use PHP’s property_exists($cls, $prop) and array_key_exists($key, $arr) functions that would fix undefined key/property issue perfectly:
echo ( array_key_exists ( ‘key2’ , $arr1 ) ? $arr1 [ ‘key2’ ] : ‘def_val’ ) . ‘
‘ ;
echo ( array_key_exists ( ‘k1’ , $arr1 ) && array_key_exists ( ‘k2’ , $arr1 [ ‘k1’ ] ) ? $arr1 [ ‘k1’ ] [ ‘k2’ ] : ‘def_val’ ) . ‘
‘ ;
echo ( property_exists ( $cls , ‘prop4’ ) ? $cls -> prop4 : ‘def_val’ ) . ‘
‘ ;
// $cls[‘prop3’][‘cls’]->prop2[‘key’] — complicated mixture of the above functions, too lazy to code.
The output will be similar to Solution1. But syntactically speaking this is not the best solution.
Solution 3 – ?? coalesce operator (>=PHP 7)
echo ( $arr1 [ ‘key2’ ] ?? ‘def_val’ ) . ‘
‘ ;
echo ( $arr1 [ ‘k1’ ] [ ‘k2’ ] ?? ‘def_val’ ) . ‘
‘ ;
echo ( $cls -> prop4 ?? ‘def_val’ ) . ‘
‘ ;
echo ( $cls [ ‘prop3’ ] [ ‘cls’ ] -> prop2 [ ‘key’ ] ) ;
Output is the same and Cannot use object of type Foo as array error still remains. But this solution seems better than others.
Solution 4 – disable warnings
$old_val = ini_get ( ‘display_errors’ ) ;
ini_set ( ‘display_errors’ , ‘off’ ) ;
echo $arr1 [ ‘key2’ ] ;
ini_set ( ‘display_errors’ , $old_val ) ;
Solution 5 – custom function
Finally, we can develop our own custom function, that will solve all of the problems. It is also possible to mix array keys and object properties in key chain list.
God, His angels and all those in Heavens and on Earth, even ants in their hills and fish in the water, call down blessings on those who instruct others in beneficial knowledge.
© Prophet Muhammad (peace be upon him)