Modify array values in a file - php

I have a php file with some arrays in it. I want to modify one of these arrays and write it back to the file. For e.g. say file test.php has contents -
<?php
$arr1 = array("a"=>"b", "c" =>"d");
$arr2 = array("a2" => "b2", "c2" => "d2");
i want to change $arr1 so that test.php now looks like -
<?php
$arr1 = array("a"=>"b", "c" =>"d", "e"=>"f");
$arr2 = array("a2" => "b2", "c2" => "d2");
I do not know what arrays are present in the file beforehand.
Edit: i am not adding any variables to the array, only another key value pair. The problem is that the array is part of a file with more arrays in it about which I won't always be aware. I can achieve this if there was only one array in the file, but want to know if it is possible to do this with multiple arrays.

You could introduce another "global" array
$arr = array('arr1' => array("a"=>"b", "c" =>"d"), 'arr2' =>("a2" => "b2", "c2" => "d2"));
and serialize it
$serArr = serialize($arr);
//write to file here
When you read the file, just unserialize its content so you have the "global" array with it's sub-arrays, modify the values you need, serialize it and write it back.
Keep in mind that this can be a huge performance issue when you write big arrays.

If you are within a function (i.e. not in global scope) get_defined_vars() might be a good bet. You'd just need to include the file in a closed scope and return it's keys to get all variable names in the file.

<?php
$arr1 = array("a"=>"b", "c" =>"d");
$newarr=array("d"=>"f");
$arr1+=$newarr;
it's has been 5 years, but i want to give simple way that work for me.

Related

PHP v5 Array Difference

I have come across two kind of arrays in PHP lately. However, I am unable to understand the main difference. I have a confusion in my mind about what these do. Can someone please enlighten me? Can I return both as associative arrays ?
$final['a']['b'] = "";
$final['c'] = "";
The difference is that the first is a 2-dimensional array, the second has only one dimension. The first is an array that contains arrays. This is nothing special, it exists in most (higher) programming and scripting languages.
Maybe it becomes clearer if you create the array with the array keyword:
Your second line would look like this:
$final = array(
"c" => ""
);
Your first line like this:
$final = array(
"a" => array(
"b" => ""
)
);

Putting file in array Php?

I have a file that has some values inside, an ordinary txt file, but I have made it look like an array
tekstovi.php
That looks like this
'1' => 'First',
'2' => 'Second',
'3' => 'Third',
Or someone have a better solution for file look :)
From that file I want to make a new array $promenjive in scope, so what is the best way to make an array from a file in php? It is easy to make explode in an ordinary array, but I don't know how to put all that in a multidimensional array :)
why don't you just make a .php file which will return an array, something like:
// somefile.php
return array(
'key1' => 'value1',
'key2' => 'value2'
);
and when you need it:
$something = require('/path/to/somefile.php');
echo $something['key1'];
Or someone have a better soluton for [the] file [format]
Create an INI file and use parse_ini_file().
If it's just an array only read by PHP, simply use include/require.
Have the file store the values in some sort of data-storing file type, e.g. xml, json, csv
PHP numerous ways of parsing and retrieving that data meaningfully. My recommendation is to use json, so with your example above it would be:
{"1":"First","2":"Second","3":"Third"}
And the corresponding PHP method to decode it:
json_decode($contents, true)
Check out the http://php.net/manual/en/function.json-decode.php for the method's full documentation, note that I set the 2nd optional argument to true since you're parsing an associative array, otherwise it will convert the data into an Object
Use JSON:
{
"foo" : "bar",
"baz" : [2, 3, 5, 7, 11]
}
PHP:
$content = file_get_contents('path/to/file');
$array = json_decode($content, true);
Et voila'.
parse_ini_file is a good solution with for a 1 or 2 dimensional array but if you need a more deeply nested structure you can use json.
$config = json_decode(file_get_contents($configFile)); // return an object, add true as a second parameter for an array instead
with the file looking something like
{
"1":"First",
"2":"Second",
"3":"Third"
}
if JSON formatting is not palatable for you then YAML or XML might be an option.
You don't need to do much, you can just create a variable in one file, and after including it will be available in the other.
file1.php:
$x = 5;
file2.php:
include file1.php
echo $x; //echoes 5

Php Variable Variables

Ive got some generated arrays, and their variable names stored in another array like the following
$array1 = 4x119 array;
$array2 = 4x119 array;
etc ..
$var1= [
"array1",
"array2",
etc...
];
and trying to loop though them like this
foreach ($var1 as $loopitem){
var_dump($$loopitem[3]);
}
How can i make this less ambiguous ?
Currenly im fairly sure its looking for a variable called the contents of $loopitem[3] instead of looking at $arr1[3] as without the [3] the var dump returns correct
Without the [3]
array(4) {
[0]=>
array(119) {
rest of output
With [3]
NULL
Any suggestions ?
You can use ${$loopitem}[3] to make it readable and unambiguous. Actually I'd always use that syntax for variable variables since $$foo is easy to misread as $foo.
However, it would be even better not to use them at all and use an array instead!

Dynamic Variables and Arrays in PHP

I have a variable that is dynamic and updates once every day from a cache file, but when I wish to display the variable it pulls nothing although my cache file has the information stored.
This is an example of what I am trying to do...
$var1 = "1"; // Dynamic info that is previously pulled from the cache file.
$var2 = array (
"0" => "2",
"1" => "3" );
Now I want to display the content of a certain part of the array...
echo "Test ".$var2['$var1'];
This is meant to output: Test 3
And if $var1 was a 0 it would output: Test 2
I have tried this many other ways, including changing the ' to ", or not even including them, it either displays a PHP error or it displays nothing apart from the "Test" text.
EDIT#1:
Ok, so this is to explain what I am doing a little bit better.
First I pull from a file and replace anything that comes with it that I don't need..
$myFile = "http://someserver.com/afile.txt";
$lines = file($myFile);
$ngender = preg_replace('/Gender=/', '', $lines[3]);
Now, I know that the above code works fine, its when I get to the array that I have problems..
$ngen = array (
1 => "Male",
2 => "Female"
);
Then I use $ngen[$ngender]; to store it into the xml file, but it don't store anything. This is actually I am trying to do before I store it into the xml file.
It should be:
echo "Test ".$var2[$var1];
$var1 is a variable so it should no be in ''.
A few things:
Not all PHP arrays are associative. The following is valid and more efficient:
$var2 = array(1 => "Male", 2 => "Female");
Variable names don't need to be stringified inside of statements. Your specific problem is caused because '$var2' would evaluate to the literal string $var2, while "$var2" would evaluate to "1".
So the correct code:
$var1 = "1"; // Dynamic info that is previously pulled from the cache file.
$var2 = array(1 => "Male", 2 => "Female");
echo "Test ".$var2[$var1];
The error you've posted on the other answer's comment suggest that $var1 isn't what you think it is. Make sure.

php arrays (and removing certain element)

I'm not 100% but this ($settings) would be called an array in php:
$setting;
$setting['host'] = "localhost";
$setting['name'] = "hello";
but what's the name for this that's different to the above:
$settings = array("localhost", "hello");
Also from the first example how can i remove the element called name?
(please also correct my terminology if I have made a mistake)
I'm not 100% but this ($settings)
would be called an array in php:
You should be 100% sure, they are :)
but what's the name for this that's
different to the above:
This:
$setting['host'] = "localhost";
$setting['name'] = "hello";
And this are different ways of declaring a php array.
$settings = array("localhost", "hello");
In fact this is how later should be to match the first one with keys:
$settings = array("host" => "localhost", "name" => "hello");
Also from the first example how can i
remove the element called name?
You can remove with unset:
unset($setting['name']);
Note that when declaring PHP array, do:
$setting = array();
Rather than:
$setting;
Note also that you can append info to arrays at the end by suffixing them with [], for example to add third element to the array, you could simply do:
$setting[] = 'Third Item';
More Information:
http://php.net/manual/en/language.types.array.php
As sAc said, they are both array. The correct way to declare an array is $settings = array(); (as opposed to just $settings; in your first line.)
The main difference between the first and second way is that the first allows you to use $settings['host'] and $settings['name'], whereas the latter can only be used with numeric indices ($settings[0] and $settings[1]). If you want to use the first way, you can also declare your array like this: $settings = array('host'=>'localhost', 'name'=>'hello');
More reading on PHP arrays
Well this is indeed an array. You have different types of array's in php. The first example you mention is called an Associative Array. Simply an array with a string as a key.
An associative array can be declared in two ways:
1) (the way you declared it):
$sample = array();
$sample["name"] = "test";
2)
$sample = array("name" => "localhost");
Furthermore the first example can also be used to add existing items to an array. For example:
$sample["name"][] = "some_name";
$sample["name"][] = "some_other_name";
When you execute the above code with print_r($sample) you get something like:
Array ( [name] => Array ( [0] => some_name [1] => some_other_name ) )
Which is very usefull when adding multiple strings to an existing array.
Removing a value from an array is very simple,
Like mentioned above, use the unset function.
unset($sample["name"])
to unset the whole name value and values connected to it
Or when you only want to unset a specific item within $sample["name"] :
unset($sample["name"][0]);
or, ofcourse any item you'd like.
So basicly.. the difference between your first example and the latter is that the first is an associative array, and the second is not.
For further reference on arrays, visit the PHP manual on arrays

Categories