Home > Back-end >  How to compact variable in laravel without knowing if they are defined
How to compact variable in laravel without knowing if they are defined

Time:08-05

I am new to laravel and I have problem. I defined bunch of unique variables and I have no idea which of them are defined. How can i compact variables if I don`t know if are they defined?

CodePudding user response:

I don't personally endorse dynamic variable names in a project.


Now that you have this situation, let's assume you create dynamic variables as below.

<?php

foreach(range(1, 20) as $num){
    ${'new_variable_' . $num} = rand(1,25);
}

My take on this would be to capture the names in a new array and pass it to compact using splat operator ... like below:

Snippet:

<?php

$vars = [];

foreach(range(1, 20) as $num){
    ${'new_variable_' . $num} = rand(1,25);
    $vars[] = 'new_variable_' . $num; // collect the names here
}

print_r(compact(...$vars));

Online Demo

CodePudding user response:

I would recommend store all the variables values in array. For example lets say you have a $title, $content and $author you have to pass from the controller to the view, you can do something like

$data = [
'title' => 'Some title',
'content' => 'Hello blah blah...',
'author' => 'Someone'
];

And then in the view file, you can output using data_get('title',$data). data_get() is a laravel helper function that you can retrieve data from array and if the key doesn't exist, you will get null instead of throwing undefined index error message.

  • Related