1
0
mirror of https://github.com/php/php-src.git synced 2026-03-25 16:52:18 +01:00

Motivated by bug #13607 I wrote up a simple array_init() function that

lets you quickly create an array and initialize each element to a certain
value.
@ Add array_init() function (Rasmus)
This commit is contained in:
Rasmus Lerdorf
2001-10-21 07:42:35 +00:00
parent 884cb737f0
commit 798ec79319
3 changed files with 52 additions and 1 deletions

View File

@@ -516,7 +516,7 @@ PHP_FUNCTION(rsort)
}
RETURN_TRUE;
}
/* }}} */
static int array_user_compare(const void *a, const void *b TSRMLS_DC)
{
@@ -1325,6 +1325,55 @@ PHP_FUNCTION(compact)
}
/* }}} */
/* {{{ proto array array_init(int start_key, int num, mixed val)
Create an array containing num elements starting with index start_key each initialized to val */
PHP_FUNCTION(array_init)
{
zval **start_key, **num, **val, *newval;
int i;
if (ZEND_NUM_ARGS() != 3 || zend_get_parameters_ex(3, &start_key, &num, &val) == FAILURE) {
WRONG_PARAM_COUNT;
}
/* allocate an array for return */
if (array_init(return_value) == FAILURE) {
RETURN_FALSE;
}
SEPARATE_ZVAL(val);
switch(Z_TYPE_PP(start_key)) {
case IS_STRING:
case IS_LONG:
case IS_DOUBLE:
convert_to_long_ex(start_key);
MAKE_STD_ZVAL(newval);
*newval = **val;
zval_copy_ctor(newval);
add_index_zval(return_value, Z_LVAL_PP(start_key), newval);
break;
default:
php_error(E_WARNING, "Wrong datatype for start key in array_init()");
RETURN_FALSE;
break;
}
convert_to_long_ex(num);
i = Z_LVAL_PP(num) - 1;
if(i<0) {
php_error(E_WARNING, "Number of elements must be positive in array_init()");
RETURN_FALSE;
}
while(i--) {
MAKE_STD_ZVAL(newval);
*newval = **val;
zval_copy_ctor(newval);
add_next_index_zval(return_value, newval);
}
}
/* }}} */
/* {{{ proto array range(mixed low, mixed high)
Create an array containing the range of integers or characters from low to high (inclusive) */
PHP_FUNCTION(range)

View File

@@ -755,6 +755,7 @@ function_entry basic_functions[] = {
PHP_FE(array_search, NULL)
PHP_FE(extract, NULL)
PHP_FE(compact, NULL)
PHP_FE(array_init, NULL)
PHP_FE(range, NULL)
PHP_FE(array_multisort, NULL)
PHP_FE(array_push, first_arg_force_ref)

View File

@@ -52,6 +52,7 @@ PHP_FUNCTION(in_array);
PHP_FUNCTION(array_search);
PHP_FUNCTION(extract);
PHP_FUNCTION(compact);
PHP_FUNCTION(array_init);
PHP_FUNCTION(range);
PHP_FUNCTION(shuffle);
PHP_FUNCTION(array_multisort);