2
$document = new Document();
$document->title = $request['title'];
$document->description = $request['description'];

When i try to output the above code using echo $document; i get this result:

{"title":"asdfasdf","description":"asdfasdfsadf"}

What i want is to create my own array of data and output the same format. This is the code i am trying to experiment but it does not work:

    $data = array(
      "title" => "hello",
      "description" => "test test test"
    );

    echo $data;

Any Help would be appreciated. Thanks.

3
  • 2
    rather you shoule use print_r($data); or dd($data); Commented Mar 21, 2018 at 5:43
  • Problem Solved? Commented Mar 21, 2018 at 5:47
  • it worked but when i tried using the dd($document) the array is wrapped inside the Document model. I also want to wrap the array that i created inside the Document model. Thanks. Commented Mar 21, 2018 at 5:55

2 Answers 2

6

All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:

foreach ($document as $data) {
    echo $data->title;
    echo $data->description;
}

There is no difference while using a PHP framework. You may refer the official PHP Arrays Manual page to work with the language construct.

If you need to convert JSON to array, use:

$data->toArray();

OR

json_decode($data);

Here is your code:

$data = array(
  "title" => "hello",
  "description" => "test test test"
);

// may also declare

$data = ["title" => "hello", "description" => "test test test"];

Use:

var_dump($data);

OR

print_r($data);

// and the output will be

["title" => "hello", "description" => "test test test",]
Sign up to request clarification or add additional context in comments.

Comments

0

foreach is also possible to traverse other structures and not just arrays:

  • List item
  • Properties of any type of object
  • Classes that extend or implement iterator in PHP Functions and methods that use generators in PHP

As we can see in the example below, the use of foreach to traverse the properties of the Local class object:

class Local {
    public string $country;
    public string $state;
    public string $city;
    public int $zipCode;

    public function __construct(string $country, string $state, string $city, int $zipCode) {
        $this->country = $country;
        $this->state = $state;
        $this->city = $city;
        $this->zipCode = $zipCode;
    }
}

$eduGouveia = new Local("Brasil", "São Paulo", "São Paulo", 2996180);

foreach ($eduGouveia as $property => $value) {
    echo $property . " - " . $value . PHP_EOL;
}

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.