PHP array_push() to create an associative array?

In PHP, array_push() is designed for indexed arrays and automatically assigns numeric keys. To create associative arrays with custom key-value pairs, use square bracket notation [] or direct assignment instead.

Why array_push() Doesn't Work for Associative Arrays

The array_push() function appends values to the end of an array with numeric indexes, which destroys associative keys ?

<?php
$arr = ['name' => 'John', 'age' => 25];
array_push($arr, 'Developer');
print_r($arr);
?>
Array
(
    [name] => John
    [age] => 25
    [0] => Developer
)

Creating Associative Arrays with Square Brackets

Use square bracket notation to add key-value pairs while preserving the associative structure ?

<?php
// Creating an associative array
$employee = [];
$employee['id'] = 101;
$employee['name'] = 'John Doe';
$employee['department'] = 'IT';
$employee['salary'] = 50000;

print_r($employee);
?>
Array
(
    [id] => 101
    [name] => John Doe
    [department] => IT
    [salary] => 50000
)

Building Arrays from Objects

You can construct associative arrays from object properties using bracket notation ?

<?php
$emp = (object) [
    'employeeId' => "101",
    'employeeFirstName' => "John", 
    'employeeLastName' => "Doe",
    'employeeCountryName' => "AUS"
];

$employeeDetails = [
    'emp_id' => $emp->employeeId,
    'emp_first_name' => $emp->employeeFirstName,
    'emp_last_name' => $emp->employeeLastName,
    'emp_country_name' => $emp->employeeCountryName
];

print_r($employeeDetails);
?>
Array
(
    [emp_id] => 101
    [emp_first_name] => John
    [emp_last_name] => Doe
    [emp_country_name] => AUS
)

Alternative: array_merge() for Associative Arrays

Use array_merge() to combine associative arrays while preserving keys ?

<?php
$arr1 = ['name' => 'John', 'age' => 25];
$arr2 = ['department' => 'IT', 'salary' => 50000];
$combined = array_merge($arr1, $arr2);

print_r($combined);
?>
Array
(
    [name] => John
    [age] => 25
    [department] => IT
    [salary] => 50000
)

Conclusion

Avoid array_push() for associative arrays as it assigns numeric keys. Use square bracket notation $arr['key'] = 'value' or array_merge() to maintain associative relationships and create properly structured key-value arrays.

Updated on: 2026-03-15T09:31:17+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements