0

I made this array for an assignment, but I can't quite get it right. What I need for it to do is recognize a string from my array and print off if "I'm learning it". I think I'm close, but I keep getting undefined offset.

 $myArray = array ("C ", "Java", "C++ ", "Objective-C", "C#", "PHP","(Visual)
                   Basic", "Python", "JavaScript", "Perl", "Ruby",
                   "PL/SQL", "Delphi/Oject pascal","Visual Basic.Net",
                   "lisp", "Pascal", "Ada", "Transact-SQL", "Logo", "NXT-G");

for ($i = 0; $i<sizeof($myArray); $i++)
    echo $myArray[$i];

if($myArray[$i] == "C") {
    echo "I'm learning this too!";
}
else {
    echo "Your not learning anything";
}
1
  • Except if using a for loop is mandatory, you can do the same using the in_array function without an explicit loop. Commented Mar 4, 2017 at 10:04

2 Answers 2

2

You are missing brackets for for loop

    $myArray = array ("C ", "Java", "C++ ", "Objective-C", "C#", "PHP","(Visual)
                   Basic", "Python", "JavaScript", "Perl", "Ruby",
                  "PL/SQL", "Delphi/Oject pascal","Visual Basic.Net",
                 "lisp", "Pasca", "Ada", "Transact-SQL", "Logo", "NXT-G");

for ($i = 0; $i< sizeof($myArray); $i++)
{
  echo $myArray[$i]."<br>";
  if($myArray[$i] == "C") {
    echo "I'm learning this too!";
  }
  else {
    echo "Your not learning anything";
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You're missing enclosing braces on the for loop.

A for loop executes the single instruction after the for command a number of times. If you want to do multiple things, you need to combine them into a block with braces { }

for ($i = 0; $i<sizeof($myArray); $i++)
{
     echo $myArray[$i];
     if($myArray[$i] == "C") 
     {
         echo "I'm learning this too!";
     }
     else
     {
         echo "Your not learning anything";
     }
}

Try and closely adhere to a layout format for your blocks, otherwise it's harder to notice when your braces don't link up properly.

Comments

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.