Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing value from array sometimes not working

This is so strange. The first one prints nothing, while if I do a die with some random text attached to it, it prints the id. Can someone please explain?

This is working:

        $product_ids = ProductToOption::groupBy('product_id')->get(['product_id']);

        foreach($product_ids as $product_id) {
            die("id: ".$product_id->product_id);
            array_push($filter_array, $product_id->product_id);
        }

But this one isn't:

        $product_ids = ProductToOption::groupBy('product_id')->get(['product_id']);

        foreach($product_ids as $product_id) {
            die($product_id->product_id);
            array_push($filter_array, $product_id->product_id);
        }
like image 555
Alvin Bakker Avatar asked Feb 08 '23 08:02

Alvin Bakker


1 Answers

If value passed to die() is an int, it won't be printed but used as return code of the process executing the script - see http://php.net/manual/en/function.exit.php for more info.

When you concatenate the int with id: the string is passed to die() instead of integer, that's why it results in id: 1 being printed.


From the manual on exit():

If status is a string, this function prints the status just before exiting.

If status is an integer, that value will be used as the exit status and not printed. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.

Note: PHP >= 4.2.0 does NOT print the status if it is an integer.

like image 127
jedrzej.kurylo Avatar answered Feb 10 '23 20:02

jedrzej.kurylo