Can you force PHP to view a numeric key as an associative array key?

Asked
Active3 hr before
Viewed126 times

8 Answers

arrayforce
90%

creates an array with a numeric key. In my development environment the array is treated as an associative array and is ordered exactly as it's built from the query. However, in production it's treating the key as a number and sorting according to the ID. If I force PHP to consider the key associative by:, 5 That is very odd... PHP does not automatically sort keys, it stores it in insertion order. Are you sure the query result is the same both times? There is actually no difference between numerical and associative arrays in PHP. It's the same data structure. – Felix Kling Oct 13 '11 at 20:21 , Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,Connect and share knowledge within a single location that is structured and easy to search.

Maybe try casting it as a string?

$results[(string) $row['id']] = $this - > get_field($row['id']);
load more v
88%

The column of values to return. This value may be an integer key of the column you wish to retrieve, or it may be a string key name for an associative array or property name. It may also be null to return complete arrays or objects (this is useful together with index_key to reindex the array). , The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name. The value is cast as usual for array keys (however, prior to PHP 8.0.0, objects supporting conversion to string were also allowed). , Returns an array of values representing a single column from the input array. , A multi-dimensional array or an array of objects from which to pull a column of values from. If an array of objects is provided, then public properties can be directly pulled. In order for protected or private properties to be pulled, the class must implement both the __get() and __isset() magic methods.

Array
   (
      [0] => John[1] => Sally[2] => Jane[3] => Peter
   )
load more v
72%

If I add an a to every index, var_dump() will show double quotes around the key, my guess to show it is now a string...,A var_dump() still shows them as integer array indexes.,Now I need to reorder these, and a var_dump() would make it appear that that isn't going to happen while the keys are integers.,It may not be completely optimal but it does allow you to sort the array and extract (an equivalent of) the original key without having to truncate anything.

I've come across an old app that uses an id to name type array, for example...

array(1) {
   [280] =>
   string(3)
   "abc"
}

If I add an a to every index, var_dump() will show double quotes around the key, my guess to show it is now a string...

array(1) {
   ["280a"] =>
   string(3)
   "abc"
}

This does not work.

$newArray = array();
foreach($array as $key => $value) {
   $newArray[(string) $key] = $value;
}
load more v
65%

Search Answer Titles

$arr = array_values($arr)
load more v
75%

Convert an object to associative array in PHP,How to delete an array element based on key in PHP?,How to convert array to string in PHP ?,Split a comma delimited string into an array in PHP

An object is an instance of a class. It is simply a specimen of a class and has memory allocated. Array is the data structure that stores one or more similar type of values in a single name but associative array is different from a simple PHP array. An array which contains string index is called associative array. It stores element values in association with key values rather than in linear index order.
Method 1: Using json_decode and json_encode method: The json_decode function accepts JSON encoded string and converts it into a PHP variable on the other hand json_encode returns a JSON encoded string for a given value.
Syntax: 
 

$myArray = json_decode(json_encode($object), true);
Output:
Before conversion:
   object(sample) #1 (2) {
  ["var1"]= >
   int(1000)["var2"] =>
   string(6)
"second"
}
After conversion:
   array(2) {
      ["var1"] =>
      int(1000)["var2"] =>
         string(6)
      "second"
   }

Method 2: Type Casting object to an array: Typecasting is the way to utilize one data type variable into the different data type and it is simply the explicit conversion of a data type. It can convert a PHP object to an array by using typecasting rules supported in PHP.
Syntax: 
 

$myArray = (array) $myObj;
Output:
Before conversion:
   object(bag) #1 (3) {
  ["item1"]= >
   string(6)
"Mobile" ["item2"] =>
string(7)
"Charger" ["item3"] =>
string(5)
"Cable"
}
After conversion:
   array(3) {
      ["item1"] =>
      string(6)
      "Mobile" ["item2"] =>
      string(7)
      "Charger" ["item3"] =>
      string(5)
      "Cable"
   }
load more v
40%

Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.,This is when I discovered numeric strings are casted to integers. ,Actually they dont have to be in numeric order... ,I've created a little function which will target the correct array element even if you only enter the integer and not the new string.

ACTUALLY YOU CAN!! Cast sequential array to associative array

$obj = new stdClass;
foreach($array as $key => $value) {
   $obj - > {
      $key
   } = $value;
}
$array = (array) $obj;
load more v
22%

The Arr::isAssoc returns true if the given array is an associative array. An array is considered "associative" if it doesn't have sequential numerical keys beginning with zero:,The Arr::wrap method wraps the given value in an array. If the given value is already an array it will be returned without modification:,The Arr::add method adds a given key / value pair to an array if the given key doesn't already exist in the array or is set to null:,The Arr::last method returns the last element of an array passing a given truth test:

The Arr::accessible method determines if the given value is array accessible:

use Illuminate\ Support\ Arr;
use Illuminate\ Support\ Collection;

$isAccessible = Arr::accessible(['a' => 1, 'b' => 2]);

// true

$isAccessible = Arr::accessible(new Collection);

// true

$isAccessible = Arr::accessible('abc');

// false

$isAccessible = Arr::accessible(new stdClass);

// false
load more v
60%

If you ever want to generate an associative array with different keys and the same value assigned to each key, you can simply use the array_fill_keys() function.,To generate an array with a given size and the same value, use array_fill():,To generate an array with a range of keys and values, like hours in the day or letters, use range():,With the extract() function, you can export an associative array to variables. For every element of an array, a variable will be created with the name of a key and value as a value of the element:

Here are a few examples of creating arrays in PHP:

$first = array(10, "Apple", 20, -18, "Monkey");
print_r($first);
/* Array
(
    [0] => 10
    [1] => Apple
    [2] => 20
    [3] => -18
    [4] => Monkey
) */

$second = [10, "Apple", 20, -18, "Monkey"];
print_r($second);
/* Array
(
    [0] => 10
    [1] => Apple
    [2] => 20
    [3] => -18
    [4] => Monkey
) */

$third = [10, 5 => "Apple", 2 => 20, -18, "Monkey"];
print_r($third);
/* Array
(
    [0] => 10
    [5] => Apple
    [2] => 20
    [6] => -18
    [7] => Monkey
) */
load more v

Other "array-force" queries related to "Can you force PHP to view a numeric key as an associative array key?"