PHP: Double square brackets after a variable? - php

echo $a['b']['b2'];
What does the value in the brackets refer to? Thanks.

This is an array.
what you are seeing is
<?php
$a = array(
'b' => array(
'b2' => 'x'
)
);
So in this case, $a['b']['b2'] will have a value of 'x'.
This is just my example though, there could be more arrays in the tree. Refer to the PHP Manual

Those are keys of a multidimensional array.
It may refer to this array:
$a = array(
"a" => array(
"a1" => "foo",
"a2" => "bar"
),
"b" => array(
"b1" => "baz",
"b2" => "bin"
)
)
In this case, $a['b']['b2'] would refer to 'bin'

This refers to a two dimensional array, and the value inside the bracket shows the key of the array

That means the variable $a holds an array. The values inside of the brackets refer the array keys.
$a = array('b' => 'somevalue', 'b2' => 'somevalue2');
In this case echo'ing $a['b'] would output it's value of 'somevalue' and $a['b2'] would output it's value of 'somevalue2'.
In your example, it's refering to a multi-dimensional array (an array inside of an array)
$a = array('b' => array('b2' => 'b2 value'));
where calling b2 would output 'b2 value'

Sorry if my answer is too simplistic, not sure your level of knowledge :)
$a is an array, a list of items. Most programming languages allow you to access items in the array using a number, but PHP also allows you to access them by a string, like 'b' or 'b2'.
Additionally, you have a two-dimensional array there - an array of arrays. So in that example, you are printing out the 'b2' element of the 'b' element in the $a array.

Related

is there a standard PHP function for transfering an associative array elements to another associative array

Is there a standard PHP function that changes an associative array's index names?
$a1 = array('one'=>1,'two'=>2,'three'=>3);
$new_index_names = array('one'=>'ono','two'=>'dos','three'=>'tres');
$a2 = change_index_names($a1,$new_index_names);
print_r($a2);
// $a2 should have the index names changed accordingly and look like this:
// array('ono'=>1,'dos'=>2,'tres'=>3)
EDIT
Please note that the function needs to know the mappings to the new index names. Meaning, in $new_index_names array provides the mappings. So again, it needs to know that 'ono' is the new index name for 'one'.
EDIT
I know you guys can come up with your own solution, i was wondering there is a standard PHP function that already does this.
EDIT
There are several situations where changing index names would help:
1) separates post value names to generic/internal names so you can separate
your backend code from front-end code.
2) say for instance you have two arrays from post that need to go through the
same exact process, except both arrays although mean/contain same exact type
of values/order/structure, they're index names are different. So when
passing to a function/method that goes by only a set of index names, you'll
need to convert the index names before passing them to that function/method.
You don't need array_values To get your desired output you can just use
array_combine($new_index_names,$a1);
not in just 1 function, but you could use array_values to get the values of the first array, and array_combine to set the new keys
Assuming both arrays has equal count, one way is with array_combine() and array_values()
$a2 = array_combine(array_values($new_index_names), $a1);
The previous answers does not consider the order of $a1 and $new_index_names, so I put my solution following:
$a1 = array('one' => 1, 'two' => 2, 'three' => 3, 'zero' => 0);
$new_index_names = array('zero' => 'zero', 'one' => 'ono', 'two' => 'dos', 'three' => 'tres');
array_combine(
$new_index_names,
str_replace(array_keys($a1), array_values($a1), array_keys($new_index_names))
);
Array
(
[zero] => 0
[ono] => 1
[dos] => 2
[tres] => 3
)
The best answer I've seen thus far:
foreach ($a1 as $k => $v) $a2[$new_index_names[$k]] = $v;
Credits go to jh1711

Filling array with its array value itself

This is an array,
$array = array(
'one' => 1,
'two' => 2,
'three' $array['one'] + $array['two']
);
It's get an error,
why?
Because $array does not exist before the end of your declaration. You simply cannot define an array on such a recursive manner since you refer to a non-existing resource.
This is a working variant. Indeed, not very convenient, but working:
<?php
$array = [
'one' => 1,
'two' => 2
];
$array['three'] = $array['one'] + $array['two'];
var_dump($array);
The output obviously is:
array(3) {
'one' =>
int(1)
'two' =>
int(2)
'three' =>
int(3)
}
The only really elegant way around this requires quite some effort:
You can implement a class implementing the ArrayAccess interface. That allows you to implement how the properties should be defined internally (for example that sum), whilst still allowing to access these properties via an array notation. So no difference to an array at runtime, only when setting up the object. However this is such a huge effort that I doubt it is worth it in >99% of the cases.
You're using a variable which is being declared, its value value is not know yet. Here is how you should write it:
$array = array(
'one' => 1,
'two' => 2,
);
$array['tree'] = $array['one'] + $array['two'];

php - Why does key of first element of an associative array cannot be zero?

I am new to associative array concept of php. I had never used associative array before this. I came through an example, and got the following code:
function isAssoc($arr)
{
return array_keys($arr) !== range(0, count($arr) - 1);
}
echo(var_dump(isAssoc(array("0" => 'a', "1" => 'b', "2" => 'c'))).'<br />'); // false
echo(var_dump(isAssoc(array("1" => 'a', "1" => 'b', "2" => 'c'))).'<br />'); //true
echo(var_dump(isAssoc(array("1" => 'a', "0" => 'b', "2" => 'c'))).'<br />'); // true
echo(var_dump(isAssoc(array("a" => 'a', "b" => 'b', "c" => 'c'))).'<br />'); // true
The above function is used to tell whether the array is associate array or not.
I have this doubt why:
array("0" => 'a', "1" => 'b', "2" => 'c')
is not an associative array as it returns false. Whereas,
array("1" => 'a', "0" => 'b', "2" => 'c') //OR
array("1" => 'a', "1" => 'b', "2" => 'c')
is an associative array?
The term "associative array" in the PHP manual is used to differentiate from "indexed array". In PHP, all arrays are by definition associative in that they contain key/value pairs (the association). However, the documentation aims to refer to "associative" when it means "non-indexed", for clarity. This is the important point.
So what is an "indexed array"? By "indexed", it is meant that the keys of the array are starting at 0 and incrementing by one. Whether the keys are explicitly set at definition (array(0 => 'a', 1 => 'b')) or implicit (array('a', 'b')) makes no difference. Any other sequence of keys would be referred to as "associative".
Note that how the PHP manual uses the term "associative" doesn't necessarily correlate precisely with the same term's use elsewhere.
All arrays in PHP are associative, you can consider it to be tuple if all keys are numeric (integers but not necessarily of that type), continuous and start from 0.
Simple check would be:
function is_assoc(array $array)
{
$keys = array_keys($array);
$keys_keys = array_keys($keys);
return $keys_keys !== $keys;
}
It would yield same results as the one you've linked to/used.
A hint here would be excerpt from json_decode documentation:
assoc
When TRUE, returned objects will be converted into associative arrays.
Even if it returns "numeric" and "indexed" array it's still associative.
Another example would be:
$array = ["0" => "a", "1" => "b", "2" => "c"]; # numeric, continuous, starts from 0
json_encode($array); # (array) ["a","b","c"]
While:
$array = ["0" => "a", "2" => "b", "3" => "c"]; # numeric, NOT continuous, starts from 0
json_encode($array); # (list) {"0":"a","2":"b","3":"c"}
The function you're referring to has flaws and it is not authoritative about the fact whether or not an array in PHP is associative or not.
In-fact, in PHP it is not strictly defined what the term associative array actually means.
However it is important to understand that
PHP is loosely typed
PHP differs in array keys between integer (bool, NULL, float, integer, numeric string represented as integer) and string (nun-numeric strings) for keys.
Most likely an associative array in PHP is one where inside the array (that is after creating it, not while it seems when writing the array definition) that all keys in that array are strings.
But keep in mind that no set-in-stone definition exists. PHP arrays are just a mixture of array and hash-map where you need to know both without having both properly differentiated and the need to keep in mind the difference between numeric and non-numeric keys and how the loosely type-system of PHP converts for the array key needs.
First page to go as usual:
http://php.net/language.types.array
For those who really can only understand it with code, here the pony goes:
function is_array_assoc(array $array) {
return is_array($array);
}
If you can ensure that you're not using an error-handler that catches catchable errors, then the following code is correct, too:
function is_array_assoc(array $array) {
return TRUE;
}
The later example makes it perhaps a bit more clear that all arrays in PHP are associative.

Can an array key be a string with embedded zero bytes?

Can an array key in PHP be a string with embedded zero-bytes?
I wanted to implode a multi-part key with embedded zero-bytes as the delimiter and use it as the key in an associative array, but it doesn't seem to be working. Not sure whether this is a problem with the array access or with array_keys_exists().
Does anybody have any idea? Am I going about this the wrong way? Should I be creating a multi-part key in another way?
To clarify, I am trying to eliminated duplicates from user-entered data. The data consists of a product ID, a variation ID, and N fields of textual data. Each of the N fields has a label and a value. To be considered a duplicate, everything must match exactly (product ID, variation ID, all the labels and all the values).
I thought that if a create a string key by concatenating the information with null bytes, I could keep an associative array to check for the presence of duplicates.
From the PHP string documentation:
There are no limitations on the values the string can be composed of;
in particular, bytes with value 0 (“NUL bytes”) are allowed anywhere
in the string (however, a few functions, said in this manual not to be
“binary safe”, may hand off the strings to libraries that ignore data
after a NUL byte.)
From the PHP arrays documentation:
A key may be either an integer or a string.
No mention is made of any special case for strings that are array keys.
So, yes.
Like I already said in the comments
print_r(array("\00foo\00bar" => 'works'));
works. However, there is no reason for any of the gymnastics you are doing with implode or serialize or null byte keys.
If you want to see whether arrays are identical, then you can just compare them:
$input1 = array('product_id' => 1, 'variation_id' => 2, 'foo' => 'bar');
$input2 = array('product_id' => 1, 'variation_id' => 2, 'foo' => 'bar');
var_dump($input1 === $input2);
will output true whereas
$input3 = array('product_id' => 1, 'variation_id' => 2, 'foo' => 'foobarbaz');
var_dump($input1 === $input3);
will give false.
Quoting the PHP Manual on Array Operators:
$a == $b Equality TRUE if $a and $b have the same key/value pairs.
$a === $b Identity TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
Also, PHP has a function for deleting duplicate values from arrays:
array_unique — Removes duplicate values from an array
And when you set the second argument to SORT_REGULAR, PHP will compare the arrays for equality, e.g.
$data = array(
array('product_id' => 1, 'variation_id' => 2, 'foo' => 'bar'),
array('product_id' => 1, 'variation_id' => 2, 'foo' => 'bar'),
array('product_id' => 2, 'variation_id' => 2, 'foo' => 'bar')
);
print_r(array_unique($data, SORT_REGULAR));
will reduce the array to only the first and the third element.

Can I store an array within a multidimensional array? (PHP)

It is possible to put an array into a multi dim array? I have a list of user settings that I want to return in a JSON array and also have another array stored in that JSON array...what is the best way to do that if it isn't possible?
A multi dimension is already an array inside an array. So there's nothing stopping you from putting another array in there. Sort of like dreams within dreams :P
Just use associative arrays if you want to give your array meaning
array(
'SETTINGS' => array(
'arr1' => array( 0, 1),
'arr2' => array( 0, 1)
),
'DATA' => array(
'arr1' => array( 0, 1),
'arr2' => array( 0, 1)
)
)
EDIT
To answer your comment, $output_files[$file_id]['shared_with'] = $shared_info; translates to (your comment had an extra ] which I removed)
$shared_info = array(1, 2, 3);
$file_id = 3;
$output_files = array(
'3' => array(
'shared_with' => array() //this is where $shared_info will get assigned
)
);
//you don't actually have to declare it an empty array. I just did it to demonstrate.
$output_files[$file_id]['shared_with'] = $shared_info; // now that empty array is replaced.
any array key can have an array value in php, as well as in json.
php:
'key' => array(...)
json:
"key" : [...]
note: php doesn't support multidimensional arrays as in C or C++. it's just an array element containing another array.

Categories