Question

I have created an array in array.php and would like to use it another file index.php How can I do this?

This is my array:

$fruits[]=array(
    "$int"=>array(
        'a' => $apple,
        'b' => $banana,
        'c' => $citrus
    )
);
Was it helpful?

Solution

You have multiple ways to do that...

  • Using http_build_query (Recommended way)
  • Using sessions.
  • Using serialization / deserialization
  • Using json_encoding / json_decoding.

and a lot other ways...

Demonstration using the second way..

array.php

<?php
//.. your code..
$arr = array(1,2,3);
header("location:index.php?value=".serialize($arr));

index.php

<?php
if(isset($_GET['value']))
{
 $arr = unserialize($_GET['value']);
 print_r($arr);
}

OTHER TIPS

Sessions work the best for this, it doesn't add the variable in the URL either.

Basically all you have to do is call

session_start();

at the top of each php page (before anything is outputted to the browser) where you want to have access to the session variables. You can then set/retrieve a variable using

// set
$_SESSION['varname'] = "something";
// retrieve
$somevar = $_SESSION['varname'];

This method allows you to use the variable on several pages too.

include("array.php"); at the position of index.php where you need the array although your question does not clearly state what you are really trying to achieve here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top