Home » Php » PHP convert array to resource

PHP convert array to resource

Posted by: admin July 12, 2020 Leave a comment


For visual representation, for simplicity and of course to feed my curiosity, I’m wondering how to convert a PHP array into a valid PHP resource.

See the below example:
enter image description here
(example image created with dBug component available at http://dbug.ospinto.com/)

I’ve made 3 examples:

  1. resource: this is the typical representation of a MySQL resource, visualized as a grid
  2. object: a handmade create object from an array
  3. array: a handmade multidimensional array

As you can see, the resource is a visual beauty, while the object and array are constructed by using multidimensional arrays, using poor numeric array indexes to bind them together 🙁

What I’m looking for, would probably be something like this:

$resource_var = (resource) $array_var;
How to&Answers:

What I’m looking for, would probably something like this:

$resource_var = (resource) $array(var)

You will never find that. A resource is an internal data-type in PHP. If (and only if) you write yourself a PHP extension and load it, you could do the following:

$resource = array_resource_create($array);

Your PHP extension then would create that resource (as the mysql extension for example creates its specific resource type) within that array_resource_create function. However, it would be useless, because there is no other function so far that could deal with that resource.


You can’t create resource. but you can use native one.

Try with curl for example.

function makeResourceFromArray($array) {

    $resource = curl_init();

    curl_setopt($resource, CURLOPT_PRIVATE, serialize($array));

    return $resource;

function makeArrayFromResource($resource) {
    return unserialize(curl_getinfo($resource, CURLINFO_PRIVATE));

$resource = makeResourceFromArray(['name' => 'test']);

$array = makeArrayFromResource($resource);


The output you show there is nothing to do with it being a resource as such, but the pretty-print function you’re using noticing that the variable you’ve given it points at a database result set, and fetching and displaying the results.

What PHP means by a resource is that the variable doesn’t actually hold data within PHP, but is a pointer or reference usable by some lower-level module of code – in this case, a DB library which can use that reference to retrieve the results of the executed query.

If you just want the pretty-print to look similar for an array with a DB-resultset-like structure, then you should simply modify the pretty-print function to do so – you don’t need to do anything to the array itself.


A resource is a special type. And a resource is specific to a source that’s external. Therefore going backwards wouldn’t be possible.

Theoretically, an interface with an instance of the resource would help manage the type – but this is just nonsense theoretical talk that is impossible in PHP.