xerox xerox - 3 months ago 7
PHP Question

Seperate php Array from main site

So, I have a page to display products which I named apple.php :

<?php
foreach($apple as $item) {
?>
<div class="col-lg-4 col-sm-4 col-xs-12 text-xs-center">
<div class="view third-effect">
<a href="<?php echo $item['link'] ?>">
<div class="overlay-thing"><i class="fa fa-share" aria-hidden="true"></i></div>
<img src="<?php echo $item['image'] ?>" />
</a>
</div>
<p><?php echo $item['name'] ?> </p>
</div>
<?php
}
?>


I use an hardcoded array which looks like this:

$apple = array(
array(
'id' => '1',
'name' => 'iPhone 4',
'link' => 'reparatur/apple/iphone-4.php',
'category' => 'iPhone',
'image' => 'images/iphone4.png'
),

array(
'id' => '2',
'name' => 'iPhone 4s',
'link' => 'reparatur/apple/iphone-4s.php',
'category' => 'iPhone',
'image' => 'images/iphone4s.png'
)
);


etc etc...

It has around 10 products.
This array is on top on the file, and I wonder how can I seperate this array into an seperate file, calling it for example products.php.

How can i then access that array in the file apple.php for the foreach loop.

Also, I will have arrays for samsung, sony products and should I put them all into the same file?

Answer

You could use include.

i.e. :

product.php

$apple = array(
    array(
        'id' => '1',
        'name' => 'iPhone 4',
        'link' => 'reparatur/apple/iphone-4.php',
        'category' => 'iPhone',
        'image' => 'images/iphone4.png'
    ),

    array(
        'id' => '2',
        'name' => 'iPhone 4s',
        'link' => 'reparatur/apple/iphone-4s.php',
        'category' => 'iPhone',
        'image' => 'images/iphone4s.png'
    )
);

apple.php

<?php 
    include 'product.php';
    foreach($apple as $item) {
 ?>
            <div class="col-lg-4 col-sm-4 col-xs-12 text-xs-center">
                <div class="view third-effect">
                    <a href="<?php echo $item['link'] ?>">
                    <div class="overlay-thing"><i class="fa fa-share" aria-hidden="true"></i></div>
                    <img src="<?php echo $item['image'] ?>" />
                    </a>
                </div>  
                <p><?php echo $item['name'] ?> </p>
            </div>
 <?php   
 }   
 ?>

Hope it helps.

Comments