-2

Say that I have a PHP array like so:

$marr = array(
"name" => "John",
"age" => 33
);

print_r($marr[0]);

This code gives me an error of Undefined offset: 0. What I am trying to achieve is to print the name part of the array without specifying it in my print request, and instead doing it via an index number. So instead of having to print $marr['name'] is there a way for me to just assign an index, much like what I tried to do in my example?

Jason Chen
  • 2,487
  • 5
  • 25
  • 44
  • 2
    PHP arrays are also dictionaries, so `'name'` is a valid index you can use, why insist on indices that are not even guaranteed? Make sure you study the PHP documentation to get a full view. – Ulrich Eckhardt Jan 30 '22 at 18:52
  • 1
    You cannot use `$marr[0]` here because you have set the key to `name` already. But even if you try to use with indexes this is not a good behavior. The array could change unexpected and you will end in different results. Just stick with the named keys. – Gkiokan Jan 30 '22 at 18:53
  • 1
    array_values($marr)[0] will work. The order is guaranteed, so note that the array must be defined so that 'name' is the first key = value pair defined. – lukas.j Jan 30 '22 at 18:56

2 Answers2

3
$marr = [
    "name" => "John",
    "age"  => 33
];

print_r(array_values($marr)[0]);

The order is guaranteed (https://www.php.net/manual/en/language.types.array.php), so as long as "name" is defined first, access with and index of 0 works.

lukas.j
  • 6,453
  • 2
  • 5
  • 24
1

In your example you have a multidimensional array. You can access by using the key to get the value. In example: echo $marr["name"]; will print you John.

You tried to access a array by index. But it doesn't work on multidimensional array. Then the array have to look like this:

$arr = [
  "John",
  "33"
];

print_r($arr[0]); // print you John

To archive this kind of array you can convert your multidimensional array with the PHP function array_values($marr). https://www.php.net/manual/de/function.array-values.php

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79