user3316523
user3316523

Reputation: 650

Undefined offset warning in php

I am doing this simple thing in php whenever i run the code i got an error

Notice: Undefined offset: 3 in C:\xampp\htdocs\colorconverter.php on line 37

this is the code that generated that error

function colorConverter($color)
{
         preg_match_all("/(\d+\.+\d+)/", $color, $rgba);
         list($rgba[0], $rgba[1], $rgba[2], $rgba[3]) = $rgba[1] ;


        $rgbaValues = array("RED"=>$rgba[0], "GREEN"=>$rgba[1], "BLUE"=>$rgba[2], "ALPHA"=>$rgba[3]);
        return $rgbaValues; 
} 

although it return correct value but why it still show an error

Upvotes: 0

Views: 100

Answers (1)

Ivan Yonkov
Ivan Yonkov

Reputation: 7034

It should be because you do not have $rgba array with 4 elements from the beginning.

Preg match all returns 2 elements 0 and 1 where second (1) is array which I guess is $rgba[1][0], $rgba[1][1], $rgba[1][2] and so on. You are trying to override $rgba[1] with its child elements.

Either declare new array and fill it with 4 empty elements, or not apply array elements in list() there should be variables:

list($rgba1, $rgba2, $rgba3, $rgba4) = $rgba[1] ;

Upvotes: 1

Related Questions