PHP: Undefined offset: 0, but not with dd ()

I get an error Undefined offset: 0with laravel. The strange thing is that with me dd()he appears.

  $ports = $container->getPorts();
  $ports = $ports[0];

It returns Undefined offset: 0

When I dd()

$ports = $container->getPorts();
dd($ports[0]);

Port {#336 
  #privatePort: 80
  #publicPort: 32780
  #type: "tcp"
}

Full array:

array:1 [โ–ผ
  0 => Port {#336 โ–ผ
    #privatePort: 80
    #publicPort: 32780
    #type: "tcp"
  }
]

I get this error with docker-php sdk. Anyone who knows what is going on?

Full code:

public function dockerContainers()
{
    $docker = new \Docker\Docker();
    $containerManager = $docker->getContainerManager();
    $containers = $containerManager->findAll();

    $data = [];
    $x=0;
    foreach ($containers as $container) {
        $ports = $container->getPorts();
        // dd($ports[0]);
        $ports = $ports[0];
        $privatePort = $ports->getPrivatePort();
        $publicPort = $ports->getPublicPort();
        $data[$x++] = [
            'id'    => $container->getId(),
            'state'  => $container->getState(),
            'names'  => $container->getNames(),
            'image'  => $container->getImage(),
            'status' => $container->getStatus(),
            'ports'  => [
                'privatePort' => $privatePort,
                'publicPort'  => $publicPort
            ]
        ];
    }

    return view('containers', [ 'containers' => $data ]);
}
+4
source share
1 answer

This is because one of yours containerdoes not ports, it is good practice to use the laravel collect () method , which turns your array into a collection object, and then you can use the available collection methods. Try the following code ...

    foreach ($containers as $container) {
            //getting ports and making laravel collection object
        $ports = collect($container->getPorts());
       if($ports->first()){
        $ports = $ports->first();
        $privatePort = $ports->getPrivatePort();
        $publicPort = $ports->getPublicPort();
        $data[$x++] = [
            'id'    => $container->getId(),
            'state'  => $container->getState(),
            'names'  => $container->getNames(),
            'image'  => $container->getImage(),
            'status' => $container->getStatus(),
            'ports'  => [
                'privatePort' => $privatePort,
                'publicPort'  => $publicPort
            ]
        ];
    }
}
0
source

Source: https://habr.com/ru/post/1687262/


All Articles