There's
trainingData = [[3, 1],[6, 1]]
How to make trainingData an array variable?
This way you can achieve.
<?php
$trainingData = '[[3, 1],[6, 1]]';
$array = json_decode($trainingData);
//Array variable
print_r($array);
?>
I'm assuming that you come from Python (or any other language that uses that kind of array defining), then you want to know how to define an array in PHP. Then there are a lot of different ways to do this but I will give you 2 fast examples:
Option 1:
<?php
$trainingData = array(
array(3,1),
array(6,1)
);
var_dump($trainingData);
Option 2 (this one mostly used when using loops to append to arrays):
<?php
$trainingData = array();
$trainingData[] = array(3,1);
$trainingData[] = array(6,1);
var_dump($trainingData);
More information and examples you can find at php docs about Arrays
Related
I just want to quickly store an array which I get from a remote API, so that i can mess around with it on a local host.
So:
I currently have an array.
I want to people to use the array without having to get it from the API.
There are no needs for efficiency etc here, this isnt for an actual site just for getting some sanitizing/formatting methods made etc
Is there a function like store_array() or restore_arrray() ?!
The best way to do this is JSON serializing. It is human readable and you'll get better performance (file is smaller and faster to load/save). The code is very easy. Just two functions
json_encode
json_decode
Example code:
$arr1 = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
file_put_contents("array.json",json_encode($arr1));
# array.json => {"a":1,"b":2,"c":3,"d":4,"e":5}
$arr2 = json_decode(file_get_contents('array.json'), true);
$arr1 === $arr2 # => true
You can write your own store_array and restore_array functions easily with this example.
For speed comparison see benchmark originally from Preferred method to store PHP arrays (json_encode vs serialize).
If you don't need the dump file to be human-readable, you can just serialize() the array.
storing:
file_put_contents('yourfile.bin', serialize($array));
retrieving:
$array = unserialize(file_get_contents('yourfile.bin'));
Use serialize and unserialize
// storing
$file = '/tmp/out.data';
file_put_contents($file, serialize($mydata)); // $mydata is the response from your remote API
// retreiving
$var = unserialize(file_get_contents($file));
Or another, hacky way:
var_export() does exactly what you want, it will take any kind of variable, and store it in a representation that the PHP parser can read back. You can combine it with file_put_contents to store it on disk, and use file_get_contents and eval to read it back.
// storing
$file = '/tmp/out.php';
file_put_contents($file, var_export($var, true));
// retrieving
eval('$myvar = ' . file_get_contents($file) . ';');
Another fast way not mentioned here:
That way add header with <?php start tag, name of variable \$my_array = with escaped \$ and footer ?> end tag.
Now can use include() like any other valid php script.
<?php
// storing
$file = '/tmp/out.php';
$var = ['a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5];
file_put_contents($file,
"<?php\n\$my_array = "
.var_export($var, true)
.";\n?>"
);
// retrieving as included script
include($file);
//testing
print_r($my_array);
?>
out.php will look like this
<?php
$my_array = array (
'a'=>1,
'b'=>2,
'c'=>3,
'd'=>4,
'e'=>5
);
?>
You can use serialize to make it into a string to write to file, and the accompanying unserialize to return it to an array structure.
I'd suggest using a language independent structure though, such as JSON. This will allow you to load the files using different languages than PHP, in case there's a chance of that later. json_encode to store it and json_decode($str, true) to return it.
Talking about php use, for performance sake, avoid encoding and decoding everything, just save array with:
file_put_contents('dic.php', "<?php \n".'$dic='.var_export($dic, true).';');
and call normally with
include "dic.php";
Use php's serialze:
file_put_contents("myFile",serialize($myArray));
I made a tiny library (~2 KB; <100 lines) that allows you to do just this: varDx
It has functions to write, read, modify, check and delete data.
It implements serialization, and therefore supports all data types.
Here's how you can use it:
<?php
require 'varDx.php';
$dx = new \varDx\cDX; //create an object
$dx->def('file.dat'); //define data file
$val1 = "this is a string";
$dx->write('data1', $val1); //writes key to file
echo $dx->read('data1'); //returns key value from file
In your specific case:
$array1 = array(
"foo" => "bar",
"bar" => "foo",
);
//writing the array to file
$dx->write('myarray', $array1);
//reading array from file
$array2 = $dx->read('myarray')
//modifying array in file after making changes
$dx->write('myarray', $array2);
Essentially I would like to create a variable with a string to be used later in array_multisort. Is this possible? E.g.
<?php
$variable = "$array['name'], SORT_ASC";
array_multisort($variable, $rows);
I realise that it's got something to do with the SORT_ASC being constant but I wouldn't know why.I also realise there might be a better way to achieve what I'm trying to do. Thanks.
You can use a multidimensional array for that purpose:
<?php
$examp = array("array" => $array,
"SORT" => SORT_ASC);
if(isset($examp)){
array_multisort($examp["array"], $examp["SORT"]);
}
?>
Question is related with example from here http://lv1.php.net/array_merge
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
Usually I use such code $result2 = array_merge( array($beginning), $end );
$end is already an array. Why need (array)$end....
Tested and see the same result.
So question. Is array_merge( array($beginning), $end ) correct code?
Seems now understood why it is reasonable to use (array)
For example $var2 = array('test2');
print_r( array($var2) );
would be multidimensional array
but
print_r( (array)$var2 );
would be the same array as initial.
There is a slight difference between array($foo) and (array)$foo, but it won't affect the output.
While array($foo) will try to build an array out of $foo, obviously returning an array, (array)$foo will try to look at$foo like it is an array, hence returning an array. Both have the exact same result if your variable is a good candidate for an array, but (array)$foo may have a stronger semantic aspect since it exposes your intention of using the variable as an array, rather than building an array out of it.
array_merge only accepts parameters of type array (Since PHP 5.0)
Convert all parameters use typecasting, therefore
Add (array) before the variable, it's means convert the data type into array, case it is not array.
Note:
If you can ensure all of the variables which used in array_merge ARE array. You can direct access it, instead of adding the (array).
Yes, it's correct code. If you are sure that the parameter is already an array you don't need the type casting.
Is it possible in php to change the name used to create an associative array? I am using mongo in php but it's getting confusing using array() in both cases of indexed arrays and associative arrays. I know you can do it in javascript by stealing the Array.prototype methods but can it be done in php my extending the native object? it would be much easier if it was array() and assoc() they would both create the same thing though.
EDIT -------
following Tristan's lead, I made this simple function to easily
write in json in php. It will even take on variable from within
your php as the whole thing is enclosed in quotes.
$one = 'newOne';
$json = "{
'$one': 1,
'two': 2
}";
// doesn't work as json_decode expects quotes.
print_r(json_decode($json));
// this does work as it replaces all the single quotes before
// using json decode.
print_r(jsonToArray($json));
function jsonToArray($str){
return json_decode(preg_replace('/\'/', '"', $str), true);
}
In PHP there is no "name used to create an associative array" or "name used to create an indexed array". PHP Arrays are ordered maps like in many other scripting languages.
This means that you can use an array whichever way you please.
If you wanted an indexed array..
$indexedArray = array();
$indexedArray[] = 4; // Append a value to the array.
echo $indexedArray[0]; // Access the value at the 0th index.
Or even..
$indexedArray = [0, 10, 12, 8];
echo $indexedArray[3]; // Outputs 8.
If you want to use non integer keys with your array, you simply specify them.
$assocArray = ['foo' => 'bar'];
echo $assocArray['foo']; // Outputs bar.
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