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" => ""
)
);
Related
I would like to expand a string with one or more values which come from an array.
Desired result:
http://example.com/search/key=["Start", "USA", "Minneapolis"]&shift=false
Array:
array(2) {
[0]=>
string(8) "USA"
[1]=>
string(4) "Minneapolis"
}
PHP Code:
$myArr = ("USA", "Minneapolis");
$string = 'http://example.com/search/key=["Start",' .$myArr[0]. ']&shift=false';
Gives me this result: http://example.com/search/key=["Start", "USA"]&shift=false
How can I make it more dynamic so that more than one value can be added? I know I somehow have to use a foreach($myArr as $i){...} and concatenate the values via $string += but because my variable is in the middle of the string I'm kinda stuck with this approach.
Try the following:
$myArr = array("USA", "Minneapolis");
$string = 'http://example.com/search/key=["Start", "' . implode('", "', $myArr) . '"]&shift=false';
This will provide the expected output using implode.
Something isn't right here. You are trying to pass array data through a querystring but not in a valid array structure. This means you are either not using it as an array on the next script and you are going to having to chop and hack at it when the data gets there.
I'll make the assumption that you would like to clean up your process...
Declare an array of all of the data that you want to pass through the url's query string, then merge the new key values into that subarray. Finally, use http_build_query() to do ALL of the work of formatting/urlencoding everything then append that generated string after the ? in your url. This is THE clean, stable way to do it.
Code: (Demo)
$myArr = ["USA", "Minneapolis", "monkey=wren[h"];
$data = [
'key' => [
'Start'
],
'shift' => 'false'
];
$data['key'] = array_merge($data['key'], $myArr);
$url = 'http://example.com/search/?' . http_build_query($data);
echo "$url\n---\n";
echo urldecode($url);
Output:
http://example.com/search/?key%5B0%5D=Start&key%5B1%5D=USA&key%5B2%5D=Minneapolis&key%5B3%5D=monkey%3Dwren%5Bh&shift=false
---
http://example.com/search/?key[0]=Start&key[1]=USA&key[2]=Minneapolis&key[3]=monkey=wren[h&shift=false
*the decoded string is just to help you to visualize the output.
Then on your receiving page, you can simply and professionally access the $_GET['key'] and $_GET['shift'] data.
If you have a legitimate reason to use your original malformed syntax, I'd love to hear it. Otherwise, please use my method for the sake of clean, valid web development.
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
I have found some code which is really confusing for me. Maybe it's my mistake or I misunderstand. I have seen some code like this:
function my_compare($a, $b) {
if ($a['practice_id']['practice_url'] == $b['practice_id']['practice-url'])
return $a['practice_location_id']['practice-url'] - $b['practice_location_id']['practise_url'];
else
return $a['practice_id']['practice_url'] - $b['practice_id']['practise_url'];
}
I just need to know the use of practice_url and practise_location_id and practice_url .
Are these both embedded in html name or value? Please help me to understand these.
$a is an associative array. "practice_id" and "practice_url" are keys. As usual, the PHP manual has good info: http://us1.php.net/manual/en/language.types.array.php.
it's a "simple" multi-dimensional php array
In php, arrays can contains number, string, object, or an other array.
for example
$a = array('practice_id' => array('practice_url' => 2));
$b = array('practice_id' => array('practice_url' => 1));
echo $a['practice_id']['practice_url']; // display "2"
This code takes two arrays of arrays. As an example:
$a = array(
'practice_id' => array(
'practice_url'=>'some url'
),
'practice_location_id' => array(
'practice-url'='some other url'
)
);
Of course without seeing the code the arrays could be anything.
$a is an array above. $a['practice_id'] refers to the array inside $a with key 'practice_id' (as an aside this is a strangely named key as it would suggest to me that the entry is a string or number rather than an array). Likewise $a['practice_id']['practice_url'] refers to the some url value.
The function is therefore just checking if certain parts of the array are equal and returning based on that. I.e.
return $a['practice_id']['practice_url'] - $b['practice_id']['practise_url'];
Note that the above is the second strange part. Either practice_url is a number and has an oddly named key or it is indeed a url and the return will attempt to convert both to an integer before returning their difference.
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!
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