Reputation: 5313
I have a list of variables like this:
<?php
$hh_1_date="Aug 29, 2012";
$hh_1_title="Data 1";
$hh_1_video="FFFnQGX0";
$hh_1_name="Peter Pan";
$hh_1_company="CompTIA";
$hh_1_image="image1.png";
$hh_1_date="Aug 30, 2012";
$hh_1_title="Data 2";
$hh_1_video="FFFRDEX0";
$hh_1_name="Peter Pooh";
$hh_1_company="CompTIA";
$hh_1_image="image2.png";
?>
And then I pull those variables into markup like this - all basic stuff...
<div class="card">
<img alt="..." class="card-img-top" src="<?php echo $hh_1_image?>">
<div class="card-body">
<span class="badge badge-pill badge-dark"><?php echo $hh_1_date ?></span>
<h5 style="color:#0c0c0e"><?php echo $hh_1_title ?></h5>
</div>
</div>
But at the moment I am copying and pasting the above HTML and changing the PHP to _2 then _3 then _4 according to its respective PHP Variable which I know is the wrong way of doing it.
So, what is a faster way? I believe it's called looping?
Thanks
Upvotes: 0
Views: 109
Reputation: 9009
You can use the get_defined_vars
(Here is the docs) function. Here is an example.
<?php
$hh_1_date="Aug 29, 2012";
$hh_1_title="Data 1";
$hh_1_video="FFFnQGX0";
$hh_1_name="Peter Pan";
$hh_1_company="CompTIA";
$hh_1_image="image1.png";
$hh_1_date="Aug 30, 2012";
$hh_1_title="Data 2";
$hh_1_video="FFFRDEX0";
$hh_1_name="Peter Pooh";
$hh_1_company="CompTIA";
$hh_1_image="image2.png";
$vars = get_defined_vars();
foreach($vars as $key => $val){
print_r($val);
}
?>
While iterating through, You'll get the variable name as key and variable's value as the value in a loop. Be careful, This method will also return the global variables defined by PHP(e.g $_SERVER
, $_POST
etc). The function get_defined_vars
returns all the variables available in current scope along with it's value.
Upvotes: 0
Reputation: 579
Put all these variables in array with key value pair and use foreach loop, like this:
$arr =[
[
'date' =>'Aug 30, 2012',
'title' => 'Data 1',
'video' => 'FFFRDEX0',
'name' => 'Peter Pooh',
'company' => 'CompTIA',
'image' => 'image1.png'
],
[
'date' =>'Aug 29, 2012',
'title' => 'Data 2',
'video' => 'FFFRDEX0',
'name' => 'Peter Pooh',
'company' => 'CompTIA',
'image' => 'image2.png'
]
....
.....
......
]
<?php foreach($arr as $k => $v): ?>
<div class="card">
<img alt="..." class="card-img-top" src="<?php echo $v['image']">
<div class="card-body">
<span class="badge badge-pill badge-dark"><?php echo $v['date'] ?></span>
<h5 style="color:#0c0c0e"><?php echo $v['title'] ?></h5>
</div>
</div>
<?php endforeach; ?>
Upvotes: 5