Php array is defined index

Undefined index: Array, when the index is defined

This is making me crazy, because I need E_ALL turned on for other reasons. I can’t get rid of this bug. Here is my function:

public static function getFileCatsString($categories) < if (empty($categories)) < return ''; >$cats = self::getFileCats(); $file_cats_string = ''; $categories_array = explode(',',$categories); foreach($categories_array as $k=>$category_id) < $file_cats_string.=$cats[$category_id].', '; >$file_cats_string = rtrim($file_cats_string, ', '); return($file_cats_string); > 

Categories are stored in keyed array: [id]=>[string] $categories that gets passed is a string of category_ids (long story as to why that is) the getFileCats() method gets a list of all available categories. So we explode the commad list to create an array, and then we loop through that array. I simply want to create, a string of category labels when I’m given a string of category ids. PHP returns this warning:

 $file_cats_string.=$cats[$category_id].', '; 

So obviously the undefined index is $cats[$category_id]. But here’s where it gets weird. If I use a die() statement and echo out $cats[$category_id] I indeed get a string, not an array. By the way, here is the output of each of the three key pieces of data with a die() statement put at the top of the foreach loop. $categories_array:

Array ( [9] => Category 19 [8] => Category 8 [7] => Category 7 [6] => Another String I Changed For Privacy [5] => AED Sales [4] => Preceptor Folder [3] => Education Brochures [2] => Forms [1] => Guidelines and Policies )

It gets weirder though. It says that the index is an array (which would indeed be a problem), so I tried putting:

 if (is_array($category_id)) < die(print_r($categories_array, true) . '
' . print_r($cats, true) . '
' . $cats[$category_id] . '
' . $category_id); >

to see if I could identify a piece of defending data, but it never dies. So what in the heck is going on?! (I have a sneaky suspicion that the answer is going to be forehead-slappingly simple.)

Читайте также:  Язык программирования javascript год создания

Источник

array_key_exists

array_key_exists() returns true if the given key is set in the array. key can be any value possible for an array index.

Parameters

An array with keys to check.

Return Values

Returns true on success or false on failure.

Note:

array_key_exists() will search for the keys in the first dimension only. Nested keys in multidimensional arrays will not be found.

Examples

Example #1 array_key_exists() example

$search_array = array( ‘first’ => 1 , ‘second’ => 4 );
if ( array_key_exists ( ‘first’ , $search_array )) echo «The ‘first’ element is in the array» ;
>
?>

Example #2 array_key_exists() vs isset()

isset() does not return true for array keys that correspond to a null value, while array_key_exists() does.

$search_array = array( ‘first’ => null , ‘second’ => 4 );

// returns false
isset( $search_array [ ‘first’ ]);

// returns true
array_key_exists ( ‘first’ , $search_array );
?>

Notes

Note:

For backward compatibility reasons, array_key_exists() will also return true if key is a property defined within an object given as array . This behaviour is deprecated as of PHP 7.4.0, and removed as of PHP 8.0.0.

To check whether a property exists in an object, property_exists() should be used.

See Also

  • isset() — Determine if a variable is declared and is different than null
  • array_keys() — Return all the keys or a subset of the keys of an array
  • in_array() — Checks if a value exists in an array
  • property_exists() — Checks if the object or class has a property

User Contributed Notes 3 notes

When you want to check multiple array keys:

$array = [];
$array [ ‘a’ ] = » ;
$array [ ‘b’ ] = » ;
$array [ ‘c’ ] = » ;
$array [ ‘d’ ] = » ;
$array [ ‘e’ ] = » ;

// all given keys a,b,c exists in the supplied array
var_dump ( array_keys_exists ([ ‘a’ , ‘b’ , ‘c’ ], $array )); // bool(true)

function array_keys_exists (array $keys , array $array ): bool
$diff = array_diff_key ( array_flip ( $keys ), $array );
return count ( $diff ) === 0 ;
>

In PHP7+ to find if a value is set in a multidimensional array with a fixed number of dimensions, simply use the Null Coalescing Operator: ??

So for a three dimensional array where you are not sure about any of the keys actually existing

// use:
$exists = array_key_exists ( $key3 , $arr [ $key1 ][ $key2 ]??[]) ;

I took hours for me to debug, and I finally recognized that,

You have to reset the $array before using array_key_exists
reset($array);
array_key_exists($needle,$array);

  • Array Functions
    • array_​change_​key_​case
    • array_​chunk
    • array_​column
    • array_​combine
    • array_​count_​values
    • array_​diff_​assoc
    • array_​diff_​key
    • array_​diff_​uassoc
    • array_​diff_​ukey
    • array_​diff
    • array_​fill_​keys
    • array_​fill
    • array_​filter
    • array_​flip
    • array_​intersect_​assoc
    • array_​intersect_​key
    • array_​intersect_​uassoc
    • array_​intersect_​ukey
    • array_​intersect
    • array_​is_​list
    • array_​key_​exists
    • array_​key_​first
    • array_​key_​last
    • array_​keys
    • array_​map
    • array_​merge_​recursive
    • array_​merge
    • array_​multisort
    • array_​pad
    • array_​pop
    • array_​product
    • array_​push
    • array_​rand
    • array_​reduce
    • array_​replace_​recursive
    • array_​replace
    • array_​reverse
    • array_​search
    • array_​shift
    • array_​slice
    • array_​splice
    • array_​sum
    • array_​udiff_​assoc
    • array_​udiff_​uassoc
    • array_​udiff
    • array_​uintersect_​assoc
    • array_​uintersect_​uassoc
    • array_​uintersect
    • array_​unique
    • array_​unshift
    • array_​values
    • array_​walk_​recursive
    • array_​walk
    • array
    • arsort
    • asort
    • compact
    • count
    • current
    • end
    • extract
    • in_​array
    • key_​exists
    • key
    • krsort
    • ksort
    • list
    • natcasesort
    • natsort
    • next
    • pos
    • prev
    • range
    • reset
    • rsort
    • shuffle
    • sizeof
    • sort
    • uasort
    • uksort
    • usort
    • each

    Источник

    How to solve PHP undefined index notice

    Posted on Aug 02, 2022

    When accessing an array in PHP, you may see a notice message that says “undefined index” as follows:

    When accessing the PHP page from the browser, the following notice message appears:

    PHP undefined index notice

    The Notice: Undefined index message means that the index key you use to access an array’s value doesn’t exist.

    In the above example, the array $my_arr only has the name index key. The age index is undefined.

    To solve this notice message, you need to make sure that the index is defined inside the array.

    The easiest way to do so is by calling the isset() function on the array index before accessing it.

    Consider the example below:

     The isset() function in PHP will make sure that the age index is defined in $my_arr .

    Combine it with an if condition to create a conditional block that runs when the array index is defined.

    Alternatively, you can also use the null coalescing operator to provide a fallback value when the index is undefined like this:

    Because the age index is undefined in the example above, the integer 29 is will be printed by the echo function.

    The null coalescing operator is useful when you have a fallback value in case the first value is undefined.

    Both isset and null coalescing operator also works when you are accessing form values with $_GET and $_POST global variable.

    Suppose you’re accessing a PHP page with the following GET parameters:

    index.php?name=nathan&age=22

    The following code checks if you have a GET parameter named age :

     Or if you want to use the null coalescing operator:
       You can use the same methods with the $_POST variable.

    Remove the undefined index notice

    While the notice message is useful, you may want to turn it off in production environment so your visitors won’t see it.

    When you don’t want the undefined index notice to appear, you can remove it by setting the error_reporting() function at the top of your PHP page.

    Now your PHP compiler will not show any notice messages, but other error messages will still be shown.

    The error_reporting() function works only for the page where you call the function.

    To make it work for all of your PHP pages, you need to set the configuration in your php.ini file as follows:

    By setting the configuration in php.ini file, all pages will not show notice messages.

    Conclusion

    Now you’ve learned what is an undefined index notice in PHP and how to resolve the message.

    You can use the isset() function or null coalescing operator to deal with an undefined index in PHP.

    You can also remove the notice message by setting the error_reporting parameter in php.ini file, or calling the error_reporting() function.

    Take your skills to the next level ⚡️

    I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

    About

    Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
    Learn statistics, JavaScript and other programming languages using clear examples written for people.

    Type the keyword below and hit enter

    Источник

    safely get array element value for defined and undefined indexes

    Admittedly, I’m not too familiar with it myself, but if you were to extend the ArrayObject class so that you had that ternary operation in the magic getter method, you could then just set it like normal.

    You could try using filter_var() as well, though that could prove almost as bulky and cumbersome. Still think the best would be to set the magic get method and pass your array to the ArrayObject.

    @J0HN — absolutely agree with you, I just wanted to get input from other developers and to make sure I don’t reinvent the wheel. @showerhead — thanks, I like this approach. simply overloading ArrayObject::offsetGet($index) does the trick.

    @Alex: Again, I have to admit I didn’t know about the offsetGet() method, I was merely talking about the magic __get() method. However, since it already has that functionality, go for it 🙂

    4 Answers 4

    PHP7 introduced the null coalesce operator ?? . Assuming you’re lucky enough to be running it, you can just do

    1) The result of accessing an undefined key is already null , so ?? null is not needed. 2) Be aware that «an E_NOTICE-level error message will be issued»: php.net/manual/en/language.types.array.php «Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL.»

    @ToolmakerSteve that is not correct. The Elvis operator suppresses the notice (just like isset does) and then returns the value on the right. Try it yourself.

    Since PHP 7.0

    $x = $array['idx'] ?? $default ?? NULL; 

    Like isset or empty it gives no warning and the expression falls through to the right (if unset). if set and not NULL the value is taken. This is also how $default in the previous example works, always, even if undefined.

    Since PHP 7.4

    Thanks to Midori Kocak — is the Null Coalescing Assignment Operator ??= Docs , RFC (which was one of the things I missed after ?? ) allows to assign default values directly:

    $array['idx'] ??= null; $x = $array['idx']; 

    I don’t use it by far as often as ?? , but it is good to know about it, especially if while break up data-handling logic and want to have defaults early.

    Original old answer

    As far as you only need NULL as «default» value, you can make use of the error suppression operator:

    Criticism: Using the error suppression operator has some downsides. First it uses the error suppression operator, so you can not easily recover issues if that part of the code has some. Additionally the standard error situation if undefined does pollute looking for screams. Your code is not as expressing itself as precise as it could be. Another potential issue is to make use of an invalid index value, e.g. injecting objects for indexes etc.. This would get unnoticed.

    It will prevent warnings. However if you like to allow other default values as well, you can encapsulate the access to an array offset via the ArrayAccess interface:

    class PigArray implements ArrayAccess < private $array; private $default; public function __construct(array $array, $default = NULL) < $this->array = $array; $this->default = $default; > public function offsetExists($offset) < return isset($this->array[$offset]); > public function offsetGet($offset) < return isset($this->array[$offset]) ? $this->array[$offset] : $this->default ; > public function offsetSet($offset, $value) < $this->array[$offset] = $value; > public function offsetUnset($offset) < unset($this->array[$offset]); > > 
    $array = array_fill_keys(range('A', 'C'), 'value'); $array = new PigArray($array, 'default'); $a = $array['A']; # string(13) "value" $idx = $array['IDX']; # NULL "default" var_dump($a, $idx); 

    Источник

Оцените статью