Documentation Home
Download this Manual
PDF (US Ltr) - 2.4Mb
PDF (A4) - 2.4Mb

MySQL PHP API  /  ...  /  CollectionModify::arrayInsert

5.10.2 CollectionModify::arrayInsert

Copyright 1997-2022 the PHP Documentation Group.

  • CollectionModify::arrayInsert

    Insert element into an array field


public mysql_xdevapi\CollectionModify mysql_xdevapi\CollectionModify::arrayInsert(string collection_field,
                                                                                  string expression_or_literal);

Add an element to a document's field, as multiple elements of a field are represented as an array. Unlike arrayAppend(), arrayInsert() allows you to specify where the new element is inserted by defining which item it is after, whereas arrayAppend() always appends the new element at the end of the array.



Identify the item in the array that the new element is inserted after. The format of this parameter is FIELD_NAME[ INDEX ] where FIELD_NAME is the name of the document field to remove the element from, and INDEX is the INDEX of the element within the field.

The INDEX field is zero based, so the leftmost item from the array has an index of 0.


The new element to insert after FIELD_NAME[ INDEX ]

Return Values

A CollectionModify object that can be used to execute the command, or to add additional operations


Example 5.41 mysql_xdevapi\CollectionModify::arrayInsert example

$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema     = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection
  '{"name":   "Bernie",
    "traits": ["Friend", "Brother", "Human"]}') 

  ->modify("name in ('Bernie', 'Jane')")
  ->arrayInsert('traits[1]', 'Happy')

$result = $collection


The above example will output something similar to:

    [0] => Array
            [_id] => 00005b6b5361000000000000010d
            [name] => Bernie
            [traits] => Array
                    [0] => Friend
                    [1] => Happy
                    [2] => Brother
                    [3] => Human