Filling array with its array value itself - php

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'];

Related

How to pass an array index or nested object property in a variable [duplicate]

This question already has answers here:
How to access and manipulate multi-dimensional array by key names / path?
(10 answers)
Closed 3 years ago.
I am trying to pass an index of associative array stored in a variable:
$a = array(
'one' => array('one' => 11, 'two' =>12),
'two' => array('one' => 21, 'two' => 22)
);
$s = "['one']['two']"; // here I am trying to assign keys to a variable for a future use
echo $a[$s]; // this usage gives error Message: Undefined index: ['one']['two']
echo $a['one']['two']; // this returns correct result (12)
The same I am trying to do within the object:
$a = array(
'one' => (object)array('one' => 11, 'two' =>12),
'two' => (object)array('one' => 21, 'two' => 22)
);
$a = (object)$a; // imagine that I receive this data from a JSON (which has much sophisticated nesting)
$s = 'one->two'; // I want to access certain object property which I receive from somewhere, hence stored in a variable
echo $a->$s; // produces error. Severity: Notice Message: Undefined property: stdClass::$one->two
echo $a->one->two; // gives correct result ("12")
How do I properly use a variable to access a value as mentioned in above examples?
Note: wrapping these into Curly brackets (i.e. complex syntax) did not work in both cases.
I assume you manually typed the ['one']['two'] part and there is no reason for it to look like that.
The by far simplest method is to explode the array indexes and loop them and that way "dig" in to the array.
$a = array(
'one' => array('one' => 11, 'two' =>12),
'two' => array('one' => 21, 'two' => 22)
);
$s = "one,two";
$res = $a;
foreach(explode(",", $s) as $item){
$res = $res[$item];
}
echo $res; // in this case echo works. But you should perhaps have if array print_r
https://3v4l.org/LeUFW
If you actually do have the one two like that then you can make it an array like this:
$s = "['one']['two']";
$s = explode("][", str_replace("'", "", trim($s, "[]")));
// $s is now an array ['one', 'two']
https://3v4l.org/YUjbn
The only solution seems to be eval() IF you trust the contents of $s:
eval( 'echo $a'.$s.';' );

How to make PhpStorm suggest / autocomplete array keys

<?php
function test(){
return array(
'one' => 1,
'two' => 2
);
}
$test = test();
echo $test[''];
I would like to put my cursor in the last line in between the single quotes, and have it suggest one or two. How can I do this?
The below works fine, so why doesn't it work inside of a function:
$test = array(
'one' => 1,
'two' => 2
);
echo $test[''];
// Suggests 'one' and 'two'
The below works fine, so why doesn't it work inside of a function:
Because it's implemented only for variables/class properties.
How can I do this?
Just install deep-assoc-completion plugin. It can do even more than that (e.g. help with completion of array parameter -- what keys are possible (if you bother to describe those keys, of course) etc).

PHP/Wordpress: Help me understand why the author of the tutorial uses array_keys() followed by array_flip()

I'm following this tutorial but have been struggling to understand a step in the insert_row() method. Here is the method in full:
// Adds new row to table
public function insert_row($data, $type='') {
global $wpdb;
// set defaults
$data = wp_parse_args( $data, $this->get_column_defaults());
do_action('add_pre_insert_' . $type, $data);
// initialise column format array
$column_formats = $this->get_columns();
// force fields to lower case
$data = array_change_key_case($data);
// remove unknown columns
$data = array_intersect_key($data, $column_formats);
// reorder $column_formats to match the order of columns in $data
$data_keys = array_keys($data);
$column_formats = array_merge(array_flip($data_keys), $column_formats);
$wpdb->insert($this->table_name, $data, $column_formats);
do_action('add_post_insert_'.$type, $wpdb->insert_id, $data);
return $wpdb->insert_id;
}
I cannot understand why the author assigns array_keys($data) to $data_keys then calls array_flip($data_keys) on the next line. What is happening there?
As I understand it, the keys of $data and array_flip($data_keys) are exactly the same. Though the values of array_flip($data_keys) would be 0,1,2,3,4,... But why? Wouldn't $column_formats overwrite those values anyway?
Ok,
So array_keys gets the keys of an array, so if you have this array
['one'=>'foo', 'two'=>'bar']
You get this from array keys:
[ 0 => 'one', 1=>'two']
Now if you flip that you get
['one' => 0, 'two' => 1]
AS to why, I have no idea. I would have to look deeper into the code and I would need some actual data that is used here.
You can test it with this bit of code (FYI I did this first bit in my head):
$a=['one'=>'foo', 'two'=>'bar'];
var_export($a);
$a = array_keys($a);
var_export($a);
$a = array_flip($a);
var_export($a);
Outputs:
array (
'one' => 'foo',
'two' => 'bar',
)array (
0 => 'one',
1 => 'two',
)array (
'one' => 0,
'two' => 1,
)
You can test it here
Once you add array_merge in any keys that exist will be replaced. Now if it was me just from a conceptual point, assuming you don't want those number in there if a key is missing, I would have used array_fill_keys instead of array_flip
$a=['one'=>'foo', 'two'=>'bar'];
var_export($a);
$a = array_keys($a);
var_export($a);
$a = array_fill_keys($a, '');
var_export($a);
Outputs
array (
'one' => 'foo',
'two' => 'bar',
)array (
0 => 'one',
1 => 'two',
)array (
'one' => '',
'two' => '',
)
As you can see the last array has just an empty string for the value, the previous way if an item is missing you get the number as the left over value. This way you would get an empty string as the left over value.
See it here
But like I said there is no way to know what their intent was without knowing what the data is that this works on. I am just "assuming" here (to make my point)

PHP: Double square brackets after a variable?

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.

Use array value while declaring an array in PHP

I was wondering...is it possible to use a value from an array which is currently being declared? Something like:
$a = array(
'foo' => 'value',
'bar' => $a['foo']
);
This is only a simple example. It would be pretty useful doing this, since it frees you from doing extra manipulation after the array declaration.
No, you can't, but you can do something like :
$a = array(
'foo' => ($val = 'value'),
'bar' => $val
);
No. $a['foo'] will only be available after the assignment completes entirely.

Categories