Muhammad Muneeb ul haq
Muhammad Muneeb ul haq

Reputation: 370

Laravel 5.4 Array to string conversion exception

I am trying to break down a string into an array and then print the values on the screen. Here is the string that i am trying to break:

"Cog|Condor"

"|" using this to split it. Here is how I am doing it:

<?= $arrays = explode('|', $b->brand); foreach($arrays as $array){echo $array;}  ?> 

But i keep getting this exception:

    2/2) ErrorException
Array to string conversion (View: D:\Code\PHP\Code\CrownBillingSystem\resources\views\pages\print.blade.php)
in 6e7ee4930110d4a26a3e31e0ddfe8b87849a1319.php (line 93)
at CompilerEngine->handleViewException(object(ErrorException), 1)
in PhpEngine.php (line 44)
at PhpEngine-

I cannot figure out what is wrong here.

Upvotes: 4

Views: 52079

Answers (4)

mbozwood
mbozwood

Reputation: 1402

While the other answers are not incorrect, Blade has been designed to eradicate the use of PHP tags. Blade functions allow you to do everything.

The error being produced here is that <?= is shorthand for <php echo. So your code will render as echo $arrays in pseudo code terms which is where the PHP is breaking because you cannot echo an array.

To better your code in this instance, you should be manipulating as much of the data as possible in the controller which is also mentioned here in the blade documentation.

Might I suggest modifying your code, to produce the same result, but using blade.

@php 
    $arrays = explode('|', $b->brand); 
@endphp

@foreach($arrays as $array)
    {{ $array }}
@endforeach

The above snippet will produce the same results as intended.

An even better way of doing it, and to further your understanding would be to return the view from the controller, and pass in $arrays predefined. Something like this:

public function echoArrays()
{
    $b = Object::find(1); //or however you get $b
    $arrays = explode('|', $b->brand); 
    return view('view1', compact('arrays');
}

The above will allow you to use the code snippet 2 up, but without the @php ...@endphp tags, and just use the @foreach() ... @endforeach

Upvotes: 5

iainn
iainn

Reputation: 17433

You can't put multiple statements in <?= ... ?> blocks - it's short-hand for echo, so your code expands to

<?php
  echo $arrays = explode('|', $b->brand); // This is what's causing your error

  foreach($arrays as $array){echo $array;}
?>

If you want to perform operations as well as output, you just need to use full PHP tags:

<?php $arrays = explode('|', $b->brand); foreach($arrays as $array){echo $array;}  ?> 

Upvotes: 4

ishegg
ishegg

Reputation: 9957

You are using the PHP short tag <?= which is equivalent to <?php echo. Thus, it's trying to echo the Array, which you can't. Do it like this:

<?php $arrays = explode('|', $b->brand); foreach($arrays as $array){echo $array;}  ?> 

Upvotes: 3

Ian Rodrigues
Ian Rodrigues

Reputation: 743

You must replace <?= by this <?php.

Upvotes: 0

Related Questions