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() . " ";
        }
    }
}

2 Answers2

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){
dWinder
  • 11,597
  • 3
  • 24
  • 39
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

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78
  • 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 – dWinder Feb 10 '19 at 12:16
  • 1
    agreed, this is just for the idea, since the error is due to accessing the object as an array. – Danyal Sandeelo Feb 10 '19 at 12:19