Hi,
is it possible to access an array element within the same array, in the way like this?
<?php
$g = array(
"min_lenght" => 3,
"errors" => array (
"lenght" => "at least $g['min_lenght'] characters!"
)
);
var_dump($g);
?>
I woud want to replace the value 3
within ["errors"]["lenght"]
, is it possible? If not, is there any other way to proceed to obtain a similar result? Thanks!
soulfx
August 10, 2016, 6:39pm
2
Yes, its possible.
Check the follow example:
<?php
$a = [
'a',
'b',
"$a[3]",
'd'
];
var_dump($a);
/* Return:
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "d"
[3]=>
string(1) "d"
}
*/
PHP write on $a[2] a link ref to $a[3], the same works when you write:
<?php
$a = "var 'a' value";
$b = $a;
echo $b; // return "var 'a' value"
Read: http://php.net/manual/en/language.references.php
Sorry, I tried but it returns error:
“Undefined variable: a”, referred to "$a[3]"
in the array.
and also, if I define $a = array();
, it returns another error:
“Undefined offset: 3”, referred to "$a[3]"
in the array.
and in both cases the value returned by "$a[3]"
appears to be string '' (length=0)
Why?
franciska:
Why?
you are trying to reference the value of position 3 when setting position 2. At that point position 3 has yet to be set - so there is no value there to copy.
soulfx
August 10, 2016, 11:11pm
5
Hum, I tried this test on php cli, and php works normally. (@edit this code not working when i tried too on php document file, just in cli…)
php > $a = ['a', 'b', "$a[3]", 'd'];
php > var_dump($a);
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "d"
[3]=>
string(1) "d"
}
php > exit
soulfx
August 11, 2016, 2:08pm
6
@franciska , you can do this too
<?php
$a = [
'totalErrros' => 2,
'format' => 'Number of errors: %s'
];
printf($a['format'], $a['totalErrros']);
3 Likes
Yes, thanks! It could be a good alternative!
system
Closed
November 11, 2016, 11:04pm
8
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.