简体   繁体   中英

How to compact variable in laravel without knowing if they are defined

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM