0

I have a file data.php, it has this code

<?php
$car[0]="BMW";$car[1]="Audi";$acr[2]="Honda";
$mob[0]="apple";$mob[1]="Nokia";$mob[2]="Sony";
?>
<html>
<body>
Some html code...
</body>
</html>

I want to create a php file that reads data.php and gives me the array named mob to use in this new file and I don't need html or other php code so include 'data.php' may not not work.

Basically, I need a php code that fetches a specific array in a different php file to reuse.

Ravi
  • 57
  • 7
  • Where does that file come from. Can you trust its content? – arkascha Apr 11 '17 at 07:11
  • Possible duplicate of [PHP, getting variable from another php-file](http://stackoverflow.com/questions/13135131/php-getting-variable-from-another-php-file) – Chirag Apr 11 '17 at 07:11

3 Answers3

2

if you only want to use them in 1 file you can do:

include 'data.php'; 

at the top of the page where you gonna need it. If you need them on multiple pages you can load them into the session.

But it has to be noted that this question is asked a lot of times. so please google before you ask : https://stackoverflow.com/a/35884027/3493752

Community
  • 1
  • 1
Christophvh
  • 12,586
  • 7
  • 48
  • 70
  • but it will include html part also, Which i dont need – Ravi Apr 11 '17 at 07:11
  • if you are gonna hardcode the data like you did, you can seperate the php variables and your html code. that way you have php file with only data. Which means no html is included. – Christophvh Apr 11 '17 at 07:12
1

You can do it easily by including you data.php file in your other file.

 include 'data.php';
 echo $car[0];
 echo $car[1];
 echo $mob[0];
 echo $mob[1];

This way you can achive your desired output.Hope it helps.

Chirag
  • 994
  • 2
  • 11
  • 26
  • If I include'data.php' , it will get the html code also. So on opening this new file these html elements will also be shown which I dont want.. – Ravi Apr 11 '17 at 07:21
  • Then loading your arrays in Session variable would be better choice. – Chirag Apr 11 '17 at 07:22
1

I don't see the purpose of doing this but you can do a separate file which returns an array of items like:

<?php

return [
    'car' => [
          'BMW',
          'Audi',
          'Honda',
     ],
    'mob' => [
          'Apple',
          'Nokia',
          'Sony',
     ]
];

On top of your file, where you want to use these items you just require the items file:

<?php
    $items = (array) include '../path/to/items.php';
?>
<html>
<body>
Some html code... <?php echo $items['car'][0] ?>
</body>
</html>

Like this you can include the items wherever you want, without including the html part too..

Mihai Matei
  • 24,166
  • 5
  • 32
  • 50