Add Elements to Array with array_push()
Adds one or more mission labels to the end of an indexed array with array_push() and returns the updated list plus the new count.
Purpose
Adds one or more mission labels to the end of an indexed array with array_push() and returns the updated list plus the new count.
Snippet details
ContextArrayLevelPracticalCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Add Elements to Array with array_push().
*
* Purpose:
* Appends scalar values to the end of an indexed array.
*
* @param array $missions Existing mission labels.
* @param array $new_missions Labels to append.
* @return array Updated mission list and count.
*/
function ogSnippetArrayPush(array $missions, array $new_missions): array {
$clean_missions = array();
foreach ($missions as $mission) {
if (is_scalar($mission) === true) {
$mission = trim((string) $mission);
if ($mission !== '') {
$clean_missions[] = $mission;
}
}
}
foreach ($new_missions as $new_mission) {
if (is_scalar($new_mission) === true) {
$new_mission = trim((string) $new_mission);
if ($new_mission !== '') {
array_push($clean_missions, $new_mission);
}
}
}
return array(
'missions' => $clean_missions,
'count' => count($clean_missions)
);
}
$push_report = ogSnippetArrayPush(
array('Enterprise refit', 'Rocinante burn'),
array('Serenity cargo run', 'SG-1 gate check')
);
echo 'Array push count: '.$push_report['count'];