0

I have an array which stores vehicles models. And i have a database table with all vehicles compatibility.

I need to through database table and find all vehicles that in array. Actually I did it and I can loop through the database with array and get all necessary information about vehicles. But my problem is I cannot save the data to the variable. For some reason it's empty.

But if i just want to display data with echo function I can actually do this.

Here is my code:

$listing = str_replace( ", ", ",", $model );
        
        $modle_arrs = explode(',', $listing);

        foreach($modle_arrs as $modle_arr){
            
            $e_compts = EbayCompatrbilityCategorie::all()->where('model', $modle_arr);
            
            $compt_val = "{";
                foreach ($e_compts as $e_compt) {
                    $compt_val .= "[" . $e_compt['year'] . "]";
                    $compt_val .= "[" . $e_compt['model'] . "]";
                    
                    echo "[" . $e_compt['year'] . "]";
                    echo "[" . $e_compt['model'] . "]";
                }
            $compt_val .= "}";

        }

        dd($compt_val);

And here is output in browser: enter image description here

How can I store data into variable in this situation?

3
  • What format is $compt_val supposed to be in? Commented Aug 23, 2017 at 1:31
  • It should be string. Commented Aug 23, 2017 at 1:55
  • Is it possible in the last iteration the query comes back empty? You're overwriting $compt_val on every iteration, so if the last query is empty, you'll get an empty string. Commented Aug 23, 2017 at 1:56

1 Answer 1

2

You are overwriting $compt_val on every iteration. If the query comes back as empty on the last iteration, $compt_val will be empty. Try keeping all the values in an array:

$listing = str_replace( ", ", ",", $model );

$modle_arrs = explode(',', $listing);
$compt_val_all = [];
foreach($modle_arrs as $modle_arr){

    $e_compts = EbayCompatrbilityCategorie::all()->where('model', $modle_arr);

    $compt_val = "{";
        foreach ($e_compts as $e_compt) {
            $compt_val .= "[" . $e_compt['year'] . "]";
            $compt_val .= "[" . $e_compt['model'] . "]";

            echo "[" . $e_compt['year'] . "]";
            echo "[" . $e_compt['model'] . "]";
        }
    $compt_val .= "}";
    $compt_val_all[] = $compt_val;
}

dd($compt_val_all);
Sign up to request clarification or add additional context in comments.

2 Comments

Great! Keep an eye out for those variable-initialization-inside-foreachs, they're easy to miss! Good luck.
One more time thanks you. Yes, I totally forgot about overwriting.

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.