-2

I have arrays in anther .php file, I want to access the array in another php, how do I go about it please?

LIKE:

first.php

<?php
$myarr = array(
array("text", "number")
);
?>

second.php

<?php
echo $myarr[0][1];
?>

to get number.

Please help.

Kingsnick
  • 9
  • 1
  • 4
    Does this answer your question? [Using the include function in PHP](https://stackoverflow.com/questions/49631265/using-the-include-function-in-php) – imposterSyndrome Oct 31 '20 at 15:43

2 Answers2

1

You need to add :

include 'first.php';

at the beginning of your file second.php

Make sure you put the right path of your file first.php

Laurent
  • 188
  • 2
  • 13
0

You can do this by many ways. Some of them may not be appropriate for your scenario. So please choose better one for your requirement.

1. Convert the array to string and pass the data using GET method.

Implode or JSON is better. Then pass the string to another file via normal get method.

first.php

<?php
$myarr = array(
array("text", "number")
);
$jsonarr=json_encode($age);
?>

second.php

<?php
$age=$_GET['age'];
$myarr=json_decode($age);
echo $myarr[0][1];
?>

2. Form submit

If you wish, form POST can also be used.The array can be converted to JSON or string as described above.

3. Pass the array as COOKIE from one file to another.

(Not recommended for large data)

first.php

<?php
$myarr = array(
array("text", "number")
);
setcookie("age", json_encode($myarr), time() + (3600), "/");
?>

second.php

<?php
$age=$_COOKIE['age'];
$myarr=json_decode($age);
echo $myarr[0][1];
?>

4. Pass the array as SESSION from one file to another.

(Not recommended for large data)

first.php

<?php
session_start();
$myarr = array(
array("text", "number")
);
$_SESSION['age']=json_encode($myarr);
?>

second.php

<?php
session_start();
$age=$_SESSION['age'];
$myarr=json_decode($age);
echo $myarr[0][1];
?>

5. PHP "include" function

The first file contains only php and if there is no HTML or php echo or print, use include function to include the first file into the second file.

second file

<?php
include "first.php";
echo $myarr[0][1];
?>

6. file_get_contents

(This will read a file into a string.)

first.php

<?php
$myarr = array(
array("text", "number")
);
echo json_encode($myarr);
?>

second.php

<?php
$jsonarr = file_get_contents("test.txt");
$myarr=json_decode($jsonarr );
echo $myarr[0][1];
?>