Arrays using file_put_contents - php

Lets say I have 2 arrays .
$arr1=array("foo"=>"bar", 1=>"one", 2=>"two");
$arr2=array("h"=>"eich", 3=>"three", 4=>"four");
By using file_put_contents I am able to print the array into a new php file something like this :
<?php
$arr1 = Array
(
"foo"=>"bar",
1=>"one",
2=>"two"
) //need a semicolon here
$arr2 = Array
(
"h"=>"eich",
3=>"three",
4=>"four"
)//need a semicolon here
My question is , How can I get a semicolon after the end of each array ?

Because you even have this problem, I guess you are looping the arrays to convert them to PHP code and not using var_export() - which you should be:
$arr1 = array("foo"=>"bar", 1=>"one", 2=>"two");
$arr2 = array("h"=>"eich", 3=>"three", 4=>"four");
$file = "<?php\n\n".var_export($arr1, TRUE).";\n\n".var_export($arr2, TRUE).";\n";
file_put_contents('newfile.php', $file);
See it working

Related

Get Text File data using in php

I have one text file in directory. I want to get contents of that text file.
in my text file
student&class&mark&grade
I am trying to my code here.
$myfile = "data.txt" ;
$getdata = file($myfile) ;
print_r($getdata) ; // student&class&mark&grade // working fine.
I'm trying to explode function
$arr = explode('&',$getdata);
print_r($arr); // not working
how to solve this problem ?
file() function return the data in array - file function
file_get_contents() return the data in string form
Try file_get_contents() - file_get_contents
$myfile = "data.txt" ;
$getdata = file_get_contents($myfile) ;
$arr = explode('&',$getdata);
print_r($arr); // Will work
file() returns an array of the lines of the file, so this is the main problem. You will also find that file() will, by default, include a new line on the end of each line - which you probably don't want.
This code uses array_walk() to process each line, using explode() on a line at a time, replacing the original line with the array.
$getdata = file($myfile, FILE_IGNORE_NEW_LINES);
array_walk ( $getdata, function ( &$data ) { $data = explode("&", $data);});
print_r($getdata);
This outputs...
Array
(
[0] => Array
(
[0] => student
[1] => class
[2] => mark
[3] => grade
)
)

php array of arrays to 1D array not getting properly as expected

I am reading value from CMD which is running a python program and my output as follows:
Let as assume those values as $A:
$A = [[1][2][3][4]....]
I want to make an array from that as:
$A = [1,2,3,4....]
I had tried as follows:
$val = str_replace("[","",$A);
$val = str_replace("]","",$val);
print_r($val);
I am getting output as:
Array ( [0] => 1 2 3 4 ... )
Please guide me
try this
// your code goes here
$array = array(
array("1"),
array("2"),
array("3"),
array("4")
);
$outputArray = array();
foreach($array as $key => $value)
{
$outputArray[] = $value[0];
}
print_r($outputArray);
Also check the example here https://ideone.com/qaxhGZ
This will work
array_reduce($a, 'array_merge', array());
Multidimensional array to single dimensional array,
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($A));
$A = iterator_to_array($it, false);
But, if $A is string
$A = '[[1][2][3][4]]';
$A = explode('][', $A);
$A = array_map(function($val){
return trim($val,'[]');
}, $A);
Both codes will get,
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
This function will work when you do indeed have a multidimensional array, which you stated you have, in stead of the String representation of a multidimensional array, which you seem to have.
function TwoDToOneDArray($TwoDArray) {
$result = array();
foreach ($TwoDArray as $value) {
array_push($result, $value[0]);
}
return $result;
}
var_dump(TwoDToOneDArray([[0],[1]]));
You can transform $A = [[1],[2],[3],[4]] into $B = [1,2,3,4....] using this following one line solution:
$B = array_map('array_shift', $A);
PD: You could not handle an array of arrays ( a matrix ) the way you did. That way is only for managing strings. And your notation was wrong. An array of arrays (a matrix) is declared with commas.
If you have a string like you wrote in the first place you can try with regex:
$a = '[[1][2][3][4]]';
preg_match_all('/\[([0-9\.]*)\]/', $a, $matches);
$a = $matches[1];
var_dump($a);
If $A is a string that looks like an array, here's one way to get it:
$A = '[[1][2][3][4]]';
print "[".str_replace(array("[","]"),array("",","),substr($A,2,strlen($A)-4))."]";
It removes [ and replaces ] with ,. I just removed the end and start brackets before the replacement and added both of them after it finishes. This outputs: [1,2,3,4] as you can see in this link.

PHP grouping single array

i want to convert single array to group array like with this:
group_1
1,2,3,4
group_2
5,6,7,8
from single array like with this:
$arr=array('1','2','3','4','5','6','7','8');
each group must be have 4 andis. and i can not programing that.
i want to have this result:
array (
'group_1'=>('1','2','3','4')
'group_2'=>('5','6','7','8')
)
my simple and wrong code:
<?php
$singleArray= array(
"arr_1",
"arr_2",
"arr_3",
"arr_4",
"arr_5",
"arr_6",
"arr_7",
"arr_8",
);
$groups = array( 'group_1','group_2' );
$groupArray = array();
foreach( $singleArray as $key=>$arr ){
if( $key != ['3','7'] ){
$groupArray[][] = $arr;
}
}
?>
Use array_chunk() to split your array into two pieces, each containing 4 elements. Now use array_combine() to create the result array using $groups as keys and the sliced array as values:
$result = array_combine($groups, array_chunk($singleArray, 4));
Demo

"Classic" array in php

So, I'm starting a new project and working with php for the first time.
I get that the average definition and functioning of arrays in php is actually pretty much a namevalue combo.
Is there some syntax, API, or other terminology for just a simple list of items?
I.e. inserting something like ['example','example2','example3','example4'] that I can just call based off their index position of the array, without having to go in and modify the syntax to include 0 => 'example', etc...
This is a very shortlived array so im not worried about long term accessibility
php arrays are simple to use. You can insert into an array like:
$array=array('a','b','c'.....);
Or
$array[]="a";
$array[]="b";
$array[]="c";
or
array_push($array, "a");
array_push($array, "b");
array_push($array, "c");
array_push($array, "d");
and call them by their index values:
$array[0];
this will give you a
$yourArray = array('a','b','c');
or
$yourArray[] = 'a';
$yourArray[] = 'b';
$yourArray[] = 'c';
will get you an array with integer index values instead of an associative one..
You still can use array as "classic" arrays in php, just the way you think.
For example :
<?php
$array = array("First", "Second", "Third");
echo $array[1];
?>
You can then add different values <?php $array[] = "Forth"; ?> and it will be indexed in the order you specified it.
Notice that you can still use it as an associative array :
<?php
$array["newValue"] = "Fifth";
$array[1] = "ReplaceTheSecond";
$array[10] = "";
?>
Arrays in PHP can either be based on a key, like 0 or "key" => "value", or values can just be "appended" to the array by using $array[] = 'value'; .
So:
$mine = array();
$mine[] = 'test';
$mine[] = 'test2';
echo $mine[0];
Would produce 'test';
Haven't tested the code.

Insert array contents into a string

I am trying to insert the contents of an array in to a string using PHP.
My array ($array1) looks like this:
Array1
(
[0] => http://www.example.com/1
[1] => http://www.example.com/2
)
I want to insert both links in to a coma separated string, so I can then insert it in to a database field.
I tried this:
foreach ($array1 as $name => $value) {
$string1 .= $value . ",";
}
echo $string1;
Which does work, but I am doing this twice in my code for another array that I also want in a separate string ($string2)
Array2
(
[0] => http://www.example.com/3
[1] => http://www.example.com/4
)
When I echo $string1 I get the correct output
http://www.example.com/1,http://www.example.com/2
But $string2 becomes this:
http://www.example.com/1,http://www.example.com/2,http://www.example.com/3,http://www.example.com/4
This happens even if I use different variable names in the foreach loop above.
Someone else also suggested I try this:
$string1 = implode(',' , $array1);
But I'm not getting any output.
Any help as to how to solve this, or any different approach is greatly appreciated!
There's a PHP function called implode for this exact purpose.
$csv = implode(',', $array);
echo $csv; //blah,blah,blah,blah
implode should work fine. It's won't give you any output unless you echo or otherwise output the result, of course.
$array1 = array("http://www.example.com/1", "http://www.example.com/2");
$array2 = array("http://www.example.com/3", "http://www.example.com/4");
echo implode(", ", array_merge($array1,$array2));
Output:
http://www.example.com/1, http://www.example.com/2, http://www.example.com/3, http://www.example.com/4

Categories