1

I'm new to PHP and I have some problem with referencing a define constant to access array:

    define('NAME_INDEX', 0);
    ...
    if( $file ) {
        while( ($line = fgets($file))!==false ) {
            $array = explode(" , ", $line);
            echo "<br>$array[NAME_INDEX]<br>";
        }
    }

The error that I received:

Notice: Undefined index: NAME_INDEX

It prints out the value that I want when I do echo $array[0] though. Might anyone know what went wrong?

6
  • Works fine for me! Please show us your entire/full/real code and the exact error message Commented Jan 24, 2015 at 22:08
  • Works for me. Are you sure the error occurs there? Commented Jan 24, 2015 at 22:08
  • You don't have quotes around it do you? $array['NAME_INDEX'] won't work. Commented Jan 24, 2015 at 22:12
  • Thanks for your comment. I've updated my full code. Instead of showing the value that I want which is the name, it returns me the Notice message as stated in my question. I'm not sure what went wrong. Commented Jan 24, 2015 at 22:15
  • "<br>".$array[NAME_INDEX]."<br>" or "<br>{$array[NAME_INDEX]}<br>"; Commented Jan 24, 2015 at 22:16

1 Answer 1

4

Just change this line:

echo "<br>$array[NAME_INDEX]<br>";

to:

echo "<br>" . $array[NAME_INDEX] . "<br>"; //OR echo "<br>{$array[NAME_INDEX]}<br>";

You can read more about concatenation in the manual: http://php.net/manual/en/language.operators.string.php

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I thought it would work because $array[0] works. 'Will accept the answer in 3 min.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.