Access array element within the same array

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!

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?

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.

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

@franciska , you can do this too :slight_smile:

<?php

    $a = [
        'totalErrros' => 2, 
        'format' => 'Number of errors: %s'
    ];

    printf($a['format'], $a['totalErrros']);
3 Likes

Yes, thanks! It could be a good alternative! :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.