Add Elements to Beginning of Array with array_unshift()
Adds one or more values to the beginning of an indexed array with array_unshift() and returns the reordered list.
Purpose
Adds one or more values to the beginning of an indexed array with array_unshift() and returns the reordered list.
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 Beginning of Array with array_unshift().
*
* Purpose:
* Prepends scalar values to an indexed array.
*
* @param array $watch_list Existing watch list values.
* @param array $priority_values Values to place at the beginning.
* @return array Updated list and count.
*/
function ogSnippetArrayUnshift(array $watch_list, array $priority_values): array {
$list = array();
foreach ($watch_list as $watch_value) {
if (is_scalar($watch_value) === true) {
$watch_value = trim((string) $watch_value);
if ($watch_value !== '') {
$list[] = $watch_value;
}
}
}
$prepend_values = array();
foreach ($priority_values as $priority_value) {
if (is_scalar($priority_value) === true) {
$priority_value = trim((string) $priority_value);
if ($priority_value !== '') {
$prepend_values[] = $priority_value;
}
}
}
if (count($prepend_values) > 0) {
array_unshift($list, ...$prepend_values);
}
return array(
'watch_list' => $list,
'count' => count($list)
);
}
$unshift_report = ogSnippetArrayUnshift(
array('LV-426 sweep', 'Cylon signal trace'),
array('Stargate iris check')
);
echo 'First watch item: '.$unshift_report['watch_list'][0];