RegEdit
RegEdit

Reputation: 2162

How to add an item to the beginning of an array?

In the script below, I need to add an item "None" with value of "" to the beginning of the array.

I'm using the $addFonts array below to do that, however, its being added to the select menu as "Array". What am I missing?

$googleFontsArray = array();
$googleFontsArrayContents = file_get_contents('http://phat-reaction.com/googlefonts.php?format=php');
$googleFontsArrayContentsArr = unserialize($googleFontsArrayContents);

$addFonts = array(
'' => 'None'
);

array_push($googleFontsArray, $addFonts);

foreach($googleFontsArrayContentsArr as $font)
{
    $googleFontsArray[$font['css-name']] = $font['font-name'];
}

Upvotes: 0

Views: 161

Answers (6)

Vinit Kadkol
Vinit Kadkol

Reputation: 1285

Add the first element in an array.

array_unshift() 
$sampleArray = array("Cat", "Dog");
array_unshift($sampleArray ,"Horse");
print_r($sampleArray); // output array - array('horse', 'cat', 'dog')

Remove first element from an array.

array_shift()

Upvotes: 1

troelskn
troelskn

Reputation: 117477

You can use the addition operator:

$a = array('Foo' => 42);
$a = array('None' => null) + $a;

Note that most people would consider it bad practice to let the position of a pair be significant, when using associative arrays. This is unique for php - other languages have either vectors (non-associative arrays) or hashmaps (Associative arrays).

Upvotes: 0

Mike Purcell
Mike Purcell

Reputation: 19979

Checkout array_unshift().

Upvotes: 2

paulsm4
paulsm4

Reputation: 121649

If you just want to add one element to the beginning of an existing array, use array_unshift():

http://www.php.net/manual/en/function.array-unshift.php

Here is a complete list of array functions:

http://www.php.net/manual/en/ref.array.php

Upvotes: 0

Vigrond
Vigrond

Reputation: 8198

Should just be

$googleFontsArray['None'] = '';

This array is associative.

Upvotes: 1

Fox
Fox

Reputation: 2368

Perhaps you want to use

array_merge($googleFontsArray, $addFonts);

?

Upvotes: 0

Related Questions