0

I want to show a specific data of an array, I have the following code and I am trying to print the printConcreteStudent function to print a specific student that I indicate passed through the variable $name.

When trying to find the student I get the following error:

Fatal error: Uncaught Error: Can not use object of type Student as array

The structure of the array is as follows:

array(1) {
  [0]=>
  object(Student)#1 (4) {
    ["name"]=>
    string(5) "Student1"
    ["lastname":"Student":private]=>
    string(7) "lastName1"
  }
}

And the function with which I am trying to print a specific data :

function printConcreteStudent($name) {

    foreach($this->students as $key=>$value){

        if($value["name"] == $name){

            echo $value->getName() . " ";
            echo $value->getLastName() . " ";
        }
    }
}
0

2 Answers 2

1

As you error state you can use object as array. In $this->students every object is of type object(Student) so you can access the name field by using "key" index. You need to change: if($value["name"] == $name){ (because cannot use $value["name"] as $value is object) to:

if($value->getName() == $name){
Sign up to request clarification or add additional context in comments.

Comments

0

students is array of object so value is an object so $value->name; is how you will access the name attribute

   foreach($this->students as $key=>$value){
     if($name==$value->name){
      //print the attributes...  
     }
   }

It's better to lower case both of the values and then compare so that it may find the result even if capital letters are entered as input

2 Comments

As Student object is may encapsulate (private member) it is better practice to use the getter for that field (as OP use in the if-scope of getName() - see my answer
agreed, this is just for the idea, since the error is due to accessing the object as an array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.