Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read array from text file?

Tags:

arrays

php

I have stored array in txt file using file_put_contents() in php, php array write successfullu in text file as same time how to read that text file into php?

<?php
$arr = array('name','rollno','address');
file_put_contents('array.txt', print_r($arr, true));
?>

The above php write text file in successfully. i want read that text file in php?

like image 659
Balakumar B Avatar asked Jul 27 '16 04:07

Balakumar B


People also ask

How do I get an array from a text file?

Use the fs. readFileSync() method to read a text file into an array in JavaScript, e.g. const contents = readFileSync(filename, 'utf-8'). split('\n') . The method will return the contents of the file, which we can split on each newline character to get an array of strings.

How do I get an array from a file?

In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method.

How do you read data in an array?

The general form for reading the data from an array is :Name of array [array index] ; Ex: marks[3] ; It can display the marks of 4th subject stored in the position 3.


2 Answers

If you plan on reusing those same values inside the array, you could use var_export on creating that array file instead.

Basic example:

$arr = array('name','rollno','address');
file_put_contents('array.txt',  '<?php return ' . var_export($arr, true) . ';');

Then, when the time comes to use those values, just use include:

$my_arr = include 'array.txt';
echo $my_arr[0]; // name

Or just use a simple JSON string, then encode / decode:

$arr = array('name','rollno','address');
file_put_contents('array.txt',  json_encode($arr));

Then, when you need it:

$my_arr = json_decode(file_get_contents('array.txt'), true);
echo $my_arr[1]; // rollno
like image 160
Kevin Avatar answered Oct 16 '22 07:10

Kevin


Use this one:

$arr = file('array.txt', FILE_IGNORE_NEW_LINES);
print_r($arr);
like image 28
hizbul25 Avatar answered Oct 16 '22 08:10

hizbul25