Php array new item

Php array new item

// Before php 5.4
$array = array(1,2,3);

// since php 5.4 , short syntax
$array = [1,2,3];

// I recommend using the short syntax if you have php version >= 5.4

Used to creating arrays like this in Perl?

Looks like we need the range() function in PHP:

$array = array_merge (array( ‘All’ ), range ( ‘A’ , ‘Z’ ));
?>

You don’t need to array_merge if it’s just one range:

There is another kind of array (php>= 5.3.0) produced by

$array = new SplFixedArray(5);

Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.

Supposing a large string-keyed array

$arr=[‘string1’=>$data1, ‘string2’=>$data2 etc. ]

when getting the keyed data with

php does *not* have to search through the array comparing each key string to the given key (‘string1’) one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it’s all hidden away.

However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :

Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It’s also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).

When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to the same zval. This is true except for value type integer.
Example:

$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => 23 ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=0, is_ref=0)int 23

but :
$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => ’23’ ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=1, is_ref=0)string ’23’ (length=2)
or :

$arr = [‘bebe’ => ‘Bob’, ‘age’ => [1,2], ‘too’ => [1,2] ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
‘too’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2

This function makes (assoc.) array creation much easier:

function arr (. $array )< return $array ; >
?>

It allows for short syntax like:

$arr = arr ( x : 1 , y : 2 , z : 3 );
?>

Instead of:

$arr = [ «x» => 1 , «y» => 2 , «z» => 3 ];
// or
$arr2 = array( «x» => 1 , «y» => 2 , «z» => 3 );
?>

Sadly PHP 8.2 doesn’t support this named arguments in the «array» function/language construct.

Источник

Insert new item in array on any position in PHP

You may find this a little more intuitive. It only requires one function call to array_splice :

$original = array( 'a', 'b', 'c', 'd', 'e' ); $inserted = array( 'x' ); // not necessarily an array, see manual quote array_splice( $original, 3, 0, $inserted ); // splice in at position 3 // $original is now a b c x d e 

If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself, an object or NULL.

RETURN VALUE: To be noted that the function does not return the desired substitution. The $original is passed by reference and edited in place. See the expression array &$array with & in the parameters list .

It’s odd that such a basic functionality is actually sort of hidden, in that the main purpose of this function as described in the documentation is something different (replace stuff in arrays). Yes, it is pointed out in the arguments section, but if you are just scanning function descriptions to find what to use to insert in arrays you would have never found it.

@JacerOmri it is totally right, both statements are valid. You can pass a value of any type, but it might not behave the same for an array, an object, or null. For scalars, type-casting (array)$scalar is equivalent to array($scalar) , but for an array, an object, or null, it will be ignored (array), convert to an array (object), or become an empty array (null) — see php.net/manual/en/…

@SunilPachlangia, adelval and others: with multi-dimensional arrays you need to wrap the replacement in an array, it’s documented. I still brought the note here so people stop doing the mistake.

A function that can insert at both integer and string positions:

/** * @param array $array * @param int|string $position * @param mixed $insert */ function array_insert(&$array, $position, $insert) < if (is_int($position)) < array_splice($array, $position, 0, $insert); >else < $pos = array_search($position, array_keys($array)); $array = array_merge( array_slice($array, 0, $pos), $insert, array_slice($array, $pos) ); >> 
$arr = ["one", "two", "three"]; array_insert( $arr, 1, "one-half" ); // -> array ( 0 => 'one', 1 => 'one-half', 2 => 'two', 3 => 'three', ) 
$arr = [ "name" => [ "type" => "string", "maxlength" => "30", ], "email" => [ "type" => "email", "maxlength" => "150", ], ]; array_insert( $arr, "email", [ "phone" => [ "type" => "string", "format" => "phone", ], ] ); // -> array ( 'name' => array ( 'type' => 'string', 'maxlength' => '30', ), 'phone' => array ( 'type' => 'string', 'format' => 'phone', ), 'email' => array ( 'type' => 'email', 'maxlength' => '150', ), ) 

The array_splice() loses the keys, whereas array_merge() does not. So the results of the first function can be very surprising. Especially because if you have two elements with the same key, only the value of the last one is kept.

We can also use $array = array_slice($array, 0, $pos) + $insert + array_slice($array, $pos); instead of array_merge function. The function will return the same output.

$a = array(1, 2, 3, 4); $b = array_merge(array_slice($a, 0, 2), array(5), array_slice($a, 2)); // $b = array(1, 2, 5, 3, 4) 

Please ignore all comments that suggest that array_merge() is inappropriate or that the array union operator is appropriate for numeric keys. Watch the union operator fail horribly.

If you want to keep the keys of the initial array and also add an array that has keys, then use the function below:

function insertArrayAtPosition( $array, $insert, $position ) < /* $array : The initial array i want to modify $insert : the new array i want to add, eg array('key' =>'value') or array('value') $position : the position where the new array will be inserted into. Please mind that arrays start at 0 */ return array_slice($array, 0, $position, TRUE) + $insert + array_slice($array, $position, NULL, TRUE); > 
$array = insertArrayAtPosition($array, array('key' => 'Value'), 3); 

This way you can insert arrays:

function array_insert(&$array, $value, $index)

This solution is misleading / poorly implemented. Here is a correction which uses array_splice() prior to merging and properly orders the element assembly. I understand why max()! is used, but it should be explained to researchers in the answer since it is covering a fringe scenario.

This function by Brad Erickson worked for me for the associative array:

/* * Inserts a new key/value after the key in the array. * * @param $key * The key to insert after. * @param $array * An array to insert in to. * @param $new_key * The key to insert. * @param $new_value * An value to insert. * * @return * The new array if the key exists, FALSE otherwise. * * @see array_insert_before() */ function array_insert_after($key, array &$array, $new_key, $new_value) < if (array_key_exists($key, $array)) < $new = array(); foreach ($array as $k =>$value) < $new[$k] = $value; if ($k === $key) < $new[$new_key] = $new_value; >> return $new; > return FALSE; > 

The function source — this blog post. There’s also handy function to insert BEFORE specific key.

There is no native PHP function (that I am aware of) that can do exactly what you requested.

I’ve written 2 methods that I believe are fit for purpose:

function insertBefore($input, $index, $element) < if (!array_key_exists($index, $input)) < throw new Exception("Index not found"); >$tmpArray = array(); $originalIndex = 0; foreach ($input as $key => $value) < if ($key === $index) < $tmpArray[] = $element; break; >$tmpArray[$key] = $value; $originalIndex++; > array_splice($input, 0, $originalIndex, $tmpArray); return $input; > function insertAfter($input, $index, $element) < if (!array_key_exists($index, $input)) < throw new Exception("Index not found"); >$tmpArray = array(); $originalIndex = 0; foreach ($input as $key => $value) < $tmpArray[$key] = $value; $originalIndex++; if ($key === $index) < $tmpArray[] = $element; break; >> array_splice($input, 0, $originalIndex, $tmpArray); return $input; > 

While faster and probably more memory efficient, this is only really suitable where it is not necessary to maintain the keys of the array.

If you do need to maintain keys, the following would be more suitable;

function insertBefore($input, $index, $newKey, $element) < if (!array_key_exists($index, $input)) < throw new Exception("Index not found"); >$tmpArray = array(); foreach ($input as $key => $value) < if ($key === $index) < $tmpArray[$newKey] = $element; >$tmpArray[$key] = $value; > return $tmpArray; > function insertAfter($input, $index, $newKey, $element) < if (!array_key_exists($index, $input)) < throw new Exception("Index not found"); >$tmpArray = array(); foreach ($input as $key => $value) < $tmpArray[$key] = $value; if ($key === $index) < $tmpArray[$newKey] = $element; >> return $tmpArray; > 

Источник

How to insert a new element in an existing array in PHP?

Now I want to make a new key value pair in each internal array present within array $topic_notes but I’m not able to do. The code which I’ve tried is as follows:

foreach ($topic_notes as $topic) < $sql = "SELECT subject_name FROM ".TBL_SUBJECTS." WHERE subject_id mt24 mb12">
    phparrays
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this question" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="question" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="1" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)">edited Nov 12, 2013 at 16:11
afuzzyllama
6,5405 gold badges47 silver badges64 bronze badges
asked Nov 12, 2013 at 16:08
3
    You're writing to the wrong reference in your foreach loop. Instead of $topic_notes['subject'] = $subject_name;, use $topic['subject'] = $subject_name; and you should be all set, since you're iterating it as $topic. Note: you'll also need to foreach($topic_notes as &$topic) to write to the iterator.
    – Michael Berkowski
    Nov 12, 2013 at 16:11
    Why not JOIN the tables and get all the info you need in one query from the very start?
    – AbraCadaver
    Nov 12, 2013 at 16:21
    possible duplicate of Insert new item in array on any position in PHP
    – Valentin Despa
    Mar 1, 2014 at 9:29
Add a comment|

4 Answers 4

Reset to default
2

You need to either get the index within your loop and set the value there or just use a reference within your for loop. By default, all items within the for loop are copiesof their original array, so changes made to it's iterated element wont be reflected.

via index

foreach ($topic_notes as $idx => $topic) < // SNIP $topic_notes[$idx]['subject'] = $subject_name; >
foreach ($topic_notes as &$topic) < // SNIP $topic['subject'] = $subject_name; >

Источник

Читайте также:  Udp server and client in python
Оцените статью