Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Implement new array function array_column() #56

Closed
wants to merge 12 commits into from

10 participants

Ben Ramsey Gustavo Lopes pierrejoye Stanislav Malyshev David Soria Parra Craig Campbell Сергей Lars Strojny Michael Moravec Nikita Popov
Ben Ramsey

array_column() returns the values of the specified column from a multi-dimensional array.

I've actually had this patch sitting around for several years, and I decided to take a look, clean it up, and finally submit it. Inspired by database methods like PDOStatement::fetchColumn(), I wrote this to scratch an itch, since I've often had the need to take a recordset array and pull a single column of values from it, which normally involves looping over the array and creating a new array of the values for the column I want to pull. I decided to implement this in the PHP core to save that step.

You can take a look at the test included to see how it works. The second parameter is the key for the column to return, which can be a number for numeric indexes or a string for associative arrays. If it can't find the column specified, it simply returns an empty array.

ext/standard/array.c
((25 lines not shown))
  2589
+			break;
  2590
+		case IS_DOUBLE:
  2591
+			index = (long)Z_DVAL_P(zoffset);
  2592
+			break;
  2593
+		case IS_BOOL:
  2594
+		case IS_LONG:
  2595
+		case IS_RESOURCE:
  2596
+			index = Z_LVAL_P(zoffset);
  2597
+			break;
  2598
+		case IS_STRING:
  2599
+			key = Z_STRVAL_P(zoffset);
  2600
+			key_len = Z_STRLEN_P(zoffset);
  2601
+			break;
  2602
+		default:
  2603
+			php_error_docref(NULL TSRMLS_CC, E_WARNING, "The key should be either a string or an integer");
  2604
+			return;
5
Stanislav Malyshev
smalyshev added a note April 14, 2012

Maybe RETURN_FALSE ? Though then I'd move the array init after the check.

Ben Ramsey
ramsey added a note April 14, 2012

I've updated this to RETURN_FALSE. I've also cleaned it up a bit by removing some of the other cases.

pierrejoye
pierrejoye added a note April 15, 2012

IS_OBJECT should be there too, calling convert_to_string if necessary (will deal with the existence of __toString or not.

pierrejoye
pierrejoye added a note April 15, 2012

convert_to_string_ex afair :)

Ben Ramsey
ramsey added a note April 15, 2012

I've added IS_OBJECT.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
ext/standard/array.c
((40 lines not shown))
  2604
+			return;
  2605
+	}
  2606
+
  2607
+	for (zend_hash_internal_pointer_reset_ex(arr_hash, &pointer);
  2608
+			zend_hash_get_current_data_ex(arr_hash, (void**)&data, &pointer) == SUCCESS;
  2609
+			zend_hash_move_forward_ex(arr_hash, &pointer)) {
  2610
+
  2611
+		if (Z_TYPE_PP(data) == IS_ARRAY) {
  2612
+			if (key && zend_hash_find(Z_ARRVAL_PP(data), key, key_len + 1, (void**)&zvalue) == FAILURE) {
  2613
+				continue;
  2614
+			} else if (!key && zend_hash_index_find(Z_ARRVAL_PP(data), index, (void**)&zvalue) == FAILURE) {
  2615
+				continue;
  2616
+			}
  2617
+
  2618
+			Z_ADDREF_PP(zvalue);
  2619
+			zend_hash_next_index_insert(HASH_OF(return_value), (void **)zvalue, sizeof(zval *), NULL);
2
Nikita Popov
nikic added a note April 14, 2012

As you already know that return_value is an array you probably should use Z_ARRVAL_P instead of HASH_OF.

Or even easier just use the add_next_index_zval API function:

add_next_index_zval(return_value, *zvalue);
Ben Ramsey
ramsey added a note April 14, 2012

Thanks. I've updated it to use add_next_index_zval().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Gustavo Lopes

I'd rather have a more general mechanism for extracting subsets of arrays, like in Mathematica:

In[6]:= {{1, 2}, {3, 4}, {5, 6, 7}}[[All, 2;;]]
Out[6]= {{2}, {4}, {6, 7}}

In[7]:= {{1, 2}, {3, 4}, {5, 6, 7}}[[All, 2]]
Out[7]= {2, 4, 6}

In[8]:= {{1, 2}, {3, 4}, {5, 6, 7}}[[{1,3}, 2]]
Out[8]= {2, 6}

but I guess this is better than nothing.

Ben Ramsey

@cataphract, can you suggest how that might look like PHP? I don't think my implementation is too far off. With some slight modifications, it might be possible to achieve something similar to what you're asking.

Ben Ramsey Merge branch 'PHP-5.3' into feature/array_column
* PHP-5.3:
  Fix bug 61746 Failing tests in ext/standard/tests/file/windows_links/*
  Fix bug 61720 ext\libxml\tests\bug61367-read.phpt fails
  Fix bug 61719 ext\soap\tests\bugs\bug31422.phpt fails
  Fix bug 61718 ext\ldap\tests\ldap_set_rebind_proc_error.phpt fails
  Fix bug 61717 ext\ldap\tests\ldap_sasl_bind_basic.phpt fails
  Fix bug 61716 tests\basic\021.phpt fails
  Fix bug 61683 tests\basic\bug20539.phpt fails
  Fix bug 61680 ext\zlib\tests\gzencode_variation1-win32.phpt fails
  Fix bug 61676 ext\tidy\tests\bug54682.phpt fails
  Fix bug 61743 tests in ext\standard\tests\file\windows_acls\* fail
b6b91f0
pierrejoye

@ramsey

btw, pls put a RFC together and send a notification mail to internals once you are ready, referring to this discussion too to avoid to have to discuss everything again from scratch :)

Gustavo Lopes

@ramsey You could for instance use null mean both All and to specify a range. This can be sorted out later. For instance, for my examples above:

array_part($foo, [null, [2, null]]);
array_part($foo, [null, 2]);
array_part($foo, [[1, 3], 2]);
Stanislav Malyshev

I think we shouldn't try to boil the ocean here. array_column is very useful on its own. If we will need super-method to do everything and make fresh coffee, we could add it later, but that IMHO should not hold adding array_column.

David Soria Parra
Owner
dsp commented June 06, 2012

Yes I agree. I think array_column is good enough to be added. I think we are still waiting for an RFC.

added some commits June 21, 2012
Ben Ramsey Merge branch 'PHP-5.3' into feature/array_column
* PHP-5.3: (160 commits)
  Remove outdated and user-specific files
  Add NEWS for bug #62262
  Fixed bug RecursiveArrayIterator does not implement Countable
  sync zip ext version with pecl
  one more correction for COM upgrading notes
  split gzgetc_basic.phpt for zlib 1.2.7
  com ext upgrading correction
  com ext upgrading info
  Reverted the BC fix regarding to #57905, test adopted
  Merge PHP 5.3.14 NEWS
  re-add 61755 to NEWS
  Make travis silent
  Adding a test for ext/posix/tests/posix_getegid_basic.phpt
  typo
  improve overflow checks
  fix potential overflow in _php_stream_scandir
  set current versions for libzip and zip ext
  updated NEWS
  zip windows fixes
  fixed bc break related to #57905
  ...
755f220
Ben Ramsey Cleaning up a memory leak. 5df46d3
Ben Ramsey
ramsey commented June 21, 2012

I finally got around to creating an RFC and submitting this to internals:

Craig Campbell

Hey @ramsey, I think think this proposal is a great idea (I do stuff like this all the time), but how do you feel about extending it slightly.

For example if you start with the following array:

$data = array(
    array('id' => 1, 'name' => 'bob', 'valid' => 1, 'email' => 'bob@yahoo.com'),
    array('id' => 2, 'name' => 'joe', 'valid' => 1, 'email' => 'joe@gmail.com'),
    array('id' => 3, 'name' => 'allison', 'valid' => 1, 'email' => 'allison@gmail.com')
);

Then you do array_column($data, 'name'); it would return

array(
    'bob',
    'joe',
    'allison
)

But what if you could do array_column($data, 'id', 'name', 'email') or array_column($data, ['id', 'name', 'email']) and have that return

array(
    'id' => array(
        1,
        2,
        3
    ),
    'name' => array(
        'bob',
        'joe',
        'allison'
    ),
    'email' => array(
        'bob@yahoo.com',
        'joe@gmail.com',
        'allison@gmail.com'
    )
)

This allows you to basically achieve the same thing but instead of having to make multiple calls you could get a bunch of arrays back in one iteration.

Not sure if this would really hurt performance in which case maybe it could be a separate method called array_columns, but I think it could be useful.

We actually do this at Vimeo quite a bit. Functions like array_multisort require the data in this format.

Сергей
Abeja commented July 12, 2012

Hello @ramsey, in my work I often use a similar function, perhaps it will be interesting to you:

function array_collect( $Items , $IndexKey , $ValueKey ) {
    if ( is_null( $IndexKey ) && is_null( $ValueKey ) || !count( $Items ) ) return $Items;
    $Result = array();
    if ( !is_null( $IndexKey ) ) {
        $Keys = is_array( $IndexKey ) ? array_values( $IndexKey ) : array( $IndexKey );
        $Key = ( is_null( end( $Keys ) ) && !array_pop( $Keys ) ) ? '[]' : '';
        $Code = '$Result[ $Item[ $Keys[ ' . implode( '] ] ][ $Item[ $Keys[ ' , array_keys( $Keys ) ) . '] ] ]' . $Key . ' = is_null( $ValueKey ) ? $Item : $Item[ $ValueKey ];';
        foreach ( $Items as $Item ) eval( $Code );
    } else
        foreach ( $Items as $Item ) 
            $Result[] = is_null( $ValueKey ) ? $Item : $Item[ $ValueKey ]; 
    return $Result;                             
}

Examples:

$records = array(
    array( 'id' => 1 , 'parent-id' => 7 , 'name' => 'Doe'),
    array( 'id' => 2 , 'parent-id' => 3 , 'name' => 'Smith'),
    array( 'id' => 4 , 'parent-id' => 7 , 'name' => 'Jones'),
);

array_collect( $records , array( 'parent-id' , 'id' ) , 'name' )
// => array( 7 => array( 1 => 'Doe' , 4 => 'Jones' ), 3 => array( 2 => 'Smith' ) )

array_collect( $records , array( 'parent-id' , null ) , 'name' )
// => array( 7 => array( 'Doe' , 'Jones' ), 3 => array ('Smith' ) )

array_collect( $records , null , 'name' )
// => array( 'Doe' , 'Smith' , 'Jones' )

array_collect( $records , 'id' , null )
/* => 
    array(
        1 => array( 'id' => 1 , 'parent-id' => 7 , 'name' => 'Doe'),
        2 => array( 'id' => 2 , 'parent-id' => 3 , 'name' => 'Smith'),
        4 => array( 'id' => 4 , 'parent-id' => 7 , 'name' => 'Jones'),
    );
*/
pierrejoye

What's the status of this PR? Are we ready to vote on the RFC?

Ben Ramsey

I need to make some changes, based on feedback.

Lars Strojny

@ramsey could you call a vote on internals on this function?

Ben Ramsey

Closing this pull request. It is superseded by pull request #257.

Ben Ramsey ramsey closed this January 11, 2013
Michael Moravec

@ramsey: Next time, there is no need for new issue, just rebase your branch and force-push it, history will be updated here automatically.

David Soria Parra dsp referenced this pull request from a commit March 20, 2013
David Soria Parra Merge branch 'pull-request/257' into PHP-5.5
* pull-request/257:
  array_column: Fix compile-time warnings
  array_column: Removed array_pluck() alias
  array_column: Set array_pluck as an alias for array_column
  array_column: Implement ability to specify an index column
  Cleaning up a memory leak.
  array_column: Adding test for IS_OBJECT and converting object to string
  array_column: Using add_next_index_zval() at nikic's recommendation.
  array_column: Improved tests
  array_column: Cleaning up, as recommended in pull request #56 comments
  Fixing typo in test for array_column()
  Simplify the code and use zend_hash_next_index_insert()
  Adding test for columns not present in all rows for array_column().
  Adding tests for the negative results of array_column()
  Implement new array function array_column()
0173c4b
David Soria Parra dsp referenced this pull request from a commit March 20, 2013
David Soria Parra Merge branch 'PHP-5.5'
* PHP-5.5:
  NEWS for array_column
  array_column: Fix compile-time warnings
  array_column: Removed array_pluck() alias
  array_column: Set array_pluck as an alias for array_column
  array_column: Implement ability to specify an index column
  Cleaning up a memory leak.
  array_column: Adding test for IS_OBJECT and converting object to string
  array_column: Using add_next_index_zval() at nikic's recommendation.
  array_column: Improved tests
  array_column: Cleaning up, as recommended in pull request #56 comments
  Fixing typo in test for array_column()
  Simplify the code and use zend_hash_next_index_insert()
  Adding test for columns not present in all rows for array_column().
  Adding tests for the negative results of array_column()
  Implement new array function array_column()
ec26c93
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Showing 12 unique commits by 1 author.

Apr 13, 2012
Ben Ramsey Implement new array function array_column()
array_column() returns the values of the specified column from a
multi-dimensional array.
993d9fe
Ben Ramsey Adding tests for the negative results of array_column() 2b81bb7
Ben Ramsey Adding test for columns not present in all rows for array_column(). 5cfca33
Apr 14, 2012
Ben Ramsey Simplify the code and use zend_hash_next_index_insert() 0a511b2
Ben Ramsey Fixing typo in test for array_column() fe86688
Ben Ramsey array_column: Cleaning up, as recommended in pull request #56 comments 6270b16
Ben Ramsey array_column: Improved tests 0a0f0ad
Ben Ramsey array_column: Using add_next_index_zval() at nikic's recommendation. 3d2a8c3
Apr 15, 2012
Ben Ramsey array_column: Adding test for IS_OBJECT and converting object to string 5eced6f
Apr 17, 2012
Ben Ramsey Merge branch 'PHP-5.3' into feature/array_column
* PHP-5.3:
  Fix bug 61746 Failing tests in ext/standard/tests/file/windows_links/*
  Fix bug 61720 ext\libxml\tests\bug61367-read.phpt fails
  Fix bug 61719 ext\soap\tests\bugs\bug31422.phpt fails
  Fix bug 61718 ext\ldap\tests\ldap_set_rebind_proc_error.phpt fails
  Fix bug 61717 ext\ldap\tests\ldap_sasl_bind_basic.phpt fails
  Fix bug 61716 tests\basic\021.phpt fails
  Fix bug 61683 tests\basic\bug20539.phpt fails
  Fix bug 61680 ext\zlib\tests\gzencode_variation1-win32.phpt fails
  Fix bug 61676 ext\tidy\tests\bug54682.phpt fails
  Fix bug 61743 tests in ext\standard\tests\file\windows_acls\* fail
b6b91f0
Jun 21, 2012
Ben Ramsey Merge branch 'PHP-5.3' into feature/array_column
* PHP-5.3: (160 commits)
  Remove outdated and user-specific files
  Add NEWS for bug #62262
  Fixed bug RecursiveArrayIterator does not implement Countable
  sync zip ext version with pecl
  one more correction for COM upgrading notes
  split gzgetc_basic.phpt for zlib 1.2.7
  com ext upgrading correction
  com ext upgrading info
  Reverted the BC fix regarding to #57905, test adopted
  Merge PHP 5.3.14 NEWS
  re-add 61755 to NEWS
  Make travis silent
  Adding a test for ext/posix/tests/posix_getegid_basic.phpt
  typo
  improve overflow checks
  fix potential overflow in _php_stream_scandir
  set current versions for libzip and zip ext
  updated NEWS
  zip windows fixes
  fixed bc break related to #57905
  ...
755f220
Ben Ramsey Cleaning up a memory leak. 5df46d3
This page is out of date. Refresh to see the latest.
58  ext/standard/array.c
@@ -2563,6 +2563,64 @@ PHP_FUNCTION(array_count_values)
2563 2563
 }
2564 2564
 /* }}} */
2565 2565
 
  2566
+/* {{{ proto array array_column(array input, mixed key)
  2567
+   Return the values from a single column in the input array, identified by the key */
  2568
+PHP_FUNCTION(array_column)
  2569
+{
  2570
+	zval *zarray, *zoffset, **data, **zvalue;
  2571
+	HashTable *arr_hash;
  2572
+	HashPosition pointer;
  2573
+	long index = 0;
  2574
+	char *key = NULL;
  2575
+	int key_len = 0;
  2576
+
  2577
+	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "az", &zarray, &zoffset) == FAILURE) {
  2578
+		return;
  2579
+	}
  2580
+
  2581
+	switch (Z_TYPE_P(zoffset)) {
  2582
+		case IS_NULL:
  2583
+			index = 0;
  2584
+			break;
  2585
+		case IS_LONG:
  2586
+			index = Z_LVAL_P(zoffset);
  2587
+			break;
  2588
+		case IS_STRING:
  2589
+			key = Z_STRVAL_P(zoffset);
  2590
+			key_len = Z_STRLEN_P(zoffset);
  2591
+			break;
  2592
+		case IS_OBJECT:
  2593
+			convert_to_string(zoffset);
  2594
+			key = Z_STRVAL_P(zoffset);
  2595
+			key_len = Z_STRLEN_P(zoffset);
  2596
+			break;
  2597
+		default:
  2598
+			php_error_docref(NULL TSRMLS_CC, E_WARNING, "The key should be either a string or an integer");
  2599
+			RETURN_FALSE;
  2600
+	}
  2601
+
  2602
+	arr_hash = Z_ARRVAL_P(zarray);
  2603
+	array_init(return_value);
  2604
+
  2605
+	for (zend_hash_internal_pointer_reset_ex(arr_hash, &pointer);
  2606
+			zend_hash_get_current_data_ex(arr_hash, (void**)&data, &pointer) == SUCCESS;
  2607
+			zend_hash_move_forward_ex(arr_hash, &pointer)) {
  2608
+
  2609
+		if (Z_TYPE_PP(data) == IS_ARRAY) {
  2610
+			if (key && zend_hash_find(Z_ARRVAL_PP(data), key, key_len + 1, (void**)&zvalue) == FAILURE) {
  2611
+				continue;
  2612
+			} else if (!key && zend_hash_index_find(Z_ARRVAL_PP(data), index, (void**)&zvalue) == FAILURE) {
  2613
+				continue;
  2614
+			}
  2615
+
  2616
+			Z_ADDREF_PP(zvalue);
  2617
+			add_next_index_zval(return_value, *zvalue);
  2618
+		}
  2619
+
  2620
+	}
  2621
+}
  2622
+/* }}} */
  2623
+
2566 2624
 /* {{{ proto array array_reverse(array input [, bool preserve keys])
2567 2625
    Return input as a new array with the order of the entries reversed */
2568 2626
 PHP_FUNCTION(array_reverse)
6  ext/standard/basic_functions.c
@@ -433,6 +433,11 @@ ZEND_BEGIN_ARG_INFO(arginfo_array_count_values, 0)
433 433
 	ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */
434 434
 ZEND_END_ARG_INFO()
435 435
 
  436
+ZEND_BEGIN_ARG_INFO_EX(arginfo_array_column, 0, 0, 2)
  437
+	ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */
  438
+	ZEND_ARG_INFO(0, key)
  439
+ZEND_END_ARG_INFO()
  440
+
436 441
 ZEND_BEGIN_ARG_INFO_EX(arginfo_array_reverse, 0, 0, 1)
437 442
 	ZEND_ARG_INFO(0, input) /* ARRAY_INFO(0, arg, 0) */
438 443
 	ZEND_ARG_INFO(0, preserve_keys)
@@ -3299,6 +3304,7 @@ const zend_function_entry basic_functions[] = { /* {{{ */
3299 3304
 	PHP_FE(array_keys,														arginfo_array_keys)
3300 3305
 	PHP_FE(array_values,													arginfo_array_values)
3301 3306
 	PHP_FE(array_count_values,												arginfo_array_count_values)
  3307
+	PHP_FE(array_column,													arginfo_array_column)
3302 3308
 	PHP_FE(array_reverse,													arginfo_array_reverse)
3303 3309
 	PHP_FE(array_reduce,													arginfo_array_reduce)
3304 3310
 	PHP_FE(array_pad,														arginfo_array_pad)
1  ext/standard/php_array.h
@@ -71,6 +71,7 @@ PHP_FUNCTION(array_replace_recursive);
71 71
 PHP_FUNCTION(array_keys);
72 72
 PHP_FUNCTION(array_values);
73 73
 PHP_FUNCTION(array_count_values);
  74
+PHP_FUNCTION(array_column);
74 75
 PHP_FUNCTION(array_reverse);
75 76
 PHP_FUNCTION(array_reduce);
76 77
 PHP_FUNCTION(array_pad);
190  ext/standard/tests/array/array_column_basic.phpt
... ...
@@ -0,0 +1,190 @@
  1
+--TEST--
  2
+Test array_column() function: basic functionality
  3
+--FILE--
  4
+<?php
  5
+/* Prototype:
  6
+ *  array array_column(array $input, mixed $key);
  7
+ * Description:
  8
+ *  Returns an array containing all the values from
  9
+ *  the specified "column" in a two-dimensional array.
  10
+ */
  11
+
  12
+echo "*** Testing array_column() : basic functionality ***\n";
  13
+/* Array representing a possible record set returned from a database */
  14
+$records = array(
  15
+	array(
  16
+		'id' => 1,
  17
+		'first_name' => 'John',
  18
+		'last_name' => 'Doe'
  19
+	),
  20
+	array(
  21
+		'id' => 2,
  22
+		'first_name' => 'Sally',
  23
+		'last_name' => 'Smith'
  24
+	),
  25
+	array(
  26
+		'id' => 3,
  27
+		'first_name' => 'Jane',
  28
+		'last_name' => 'Jones'
  29
+	)
  30
+);
  31
+
  32
+echo "-- first_name column from recordset --\n";
  33
+var_dump(array_column($records, 'first_name'));
  34
+
  35
+echo "-- id column from recordset --\n";
  36
+var_dump(array_column($records, 'id'));
  37
+
  38
+echo "\n*** Testing multiple data types ***\n";
  39
+$file = basename(__FILE__);
  40
+$fh = fopen($file, 'r', true);
  41
+$values = array(
  42
+	array(
  43
+		'id' => 1,
  44
+		'value' => new stdClass
  45
+	),
  46
+	array(
  47
+		'id' => 2,
  48
+		'value' => 34.2345
  49
+	),
  50
+	array(
  51
+		'id' => 3,
  52
+		'value' => true
  53
+	),
  54
+	array(
  55
+		'id' => 4,
  56
+		'value' => false
  57
+	),
  58
+	array(
  59
+		'id' => 5,
  60
+		'value' => null
  61
+	),
  62
+	array(
  63
+		'id' => 6,
  64
+		'value' => 1234
  65
+	),
  66
+	array(
  67
+		'id' => 7,
  68
+		'value' => 'Foo'
  69
+	),
  70
+	array(
  71
+		'id' => 8,
  72
+		'value' => $fh
  73
+	)
  74
+);
  75
+var_dump(array_column($values, 'value'));
  76
+
  77
+echo "\n*** Testing numeric column keys ***\n";
  78
+$numericCols = array(
  79
+	array('aaa', '111'),
  80
+	array('bbb', '222'),
  81
+	array('ccc', '333')
  82
+);
  83
+var_dump(array_column($numericCols, 1));
  84
+
  85
+echo "\n*** Testing failure to find specified column ***\n";
  86
+var_dump(array_column($numericCols, 2));
  87
+var_dump(array_column($numericCols, 'foo'));
  88
+
  89
+echo "\n*** Testing single dimensional array ***\n";
  90
+$singleDimension = array('foo', 'bar', 'baz');
  91
+var_dump(array_column($singleDimension, 1));
  92
+
  93
+echo "\n*** Testing columns not present in all rows ***\n";
  94
+$mismatchedColumns = array(
  95
+    array('a' => 'foo', 'b' => 'bar'),
  96
+    array('a' => 'baz', 'c' => 'qux'),
  97
+);
  98
+var_dump(array_column($mismatchedColumns, 'c'));
  99
+
  100
+echo "\n*** Testing use of object converted to string ***\n";
  101
+class Foo
  102
+{
  103
+    public function __toString()
  104
+    {
  105
+        return 'last_name';
  106
+    }
  107
+}
  108
+$f = new Foo();
  109
+var_dump(array_column($records, $f));
  110
+
  111
+echo "Done\n";
  112
+?>
  113
+--EXPECTF--
  114
+*** Testing array_column() : basic functionality ***
  115
+-- first_name column from recordset --
  116
+array(3) {
  117
+  [0]=>
  118
+  string(4) "John"
  119
+  [1]=>
  120
+  string(5) "Sally"
  121
+  [2]=>
  122
+  string(4) "Jane"
  123
+}
  124
+-- id column from recordset --
  125
+array(3) {
  126
+  [0]=>
  127
+  int(1)
  128
+  [1]=>
  129
+  int(2)
  130
+  [2]=>
  131
+  int(3)
  132
+}
  133
+
  134
+*** Testing multiple data types ***
  135
+array(8) {
  136
+  [0]=>
  137
+  object(stdClass)#1 (0) {
  138
+  }
  139
+  [1]=>
  140
+  float(34.2345)
  141
+  [2]=>
  142
+  bool(true)
  143
+  [3]=>
  144
+  bool(false)
  145
+  [4]=>
  146
+  NULL
  147
+  [5]=>
  148
+  int(1234)
  149
+  [6]=>
  150
+  string(3) "Foo"
  151
+  [7]=>
  152
+  resource(5) of type (stream)
  153
+}
  154
+
  155
+*** Testing numeric column keys ***
  156
+array(3) {
  157
+  [0]=>
  158
+  string(3) "111"
  159
+  [1]=>
  160
+  string(3) "222"
  161
+  [2]=>
  162
+  string(3) "333"
  163
+}
  164
+
  165
+*** Testing failure to find specified column ***
  166
+array(0) {
  167
+}
  168
+array(0) {
  169
+}
  170
+
  171
+*** Testing single dimensional array ***
  172
+array(0) {
  173
+}
  174
+
  175
+*** Testing columns not present in all rows ***
  176
+array(1) {
  177
+  [0]=>
  178
+  string(3) "qux"
  179
+}
  180
+
  181
+*** Testing use of object converted to string ***
  182
+array(3) {
  183
+  [0]=>
  184
+  string(3) "Doe"
  185
+  [1]=>
  186
+  string(5) "Smith"
  187
+  [2]=>
  188
+  string(5) "Jones"
  189
+}
  190
+Done
82  ext/standard/tests/array/array_column_error.phpt
... ...
@@ -0,0 +1,82 @@
  1
+--TEST--
  2
+Test array_column() function: error conditions
  3
+--FILE--
  4
+<?php
  5
+/* Prototype:
  6
+ *  array array_column(array $input, mixed $key);
  7
+ * Description:
  8
+ *  Returns an array containing all the values from
  9
+ *  the specified "column" in a two-dimensional array.
  10
+ */
  11
+
  12
+echo "*** Testing array_column() : error conditions ***\n";
  13
+
  14
+echo "\n-- Testing array_column() function with Zero arguments --\n";
  15
+var_dump(array_column());
  16
+
  17
+echo "\n-- Testing array_column() function with One argument --\n";
  18
+var_dump(array_column(array()));
  19
+
  20
+echo "\n-- Testing array_column() function with more than expected no. of arguments --\n";
  21
+var_dump(array_column(array(), 'foo', 'bar'));
  22
+
  23
+echo "\n-- Testing array_column() function with string as first parameter --\n";
  24
+var_dump(array_column('foo', 0));
  25
+
  26
+echo "\n-- Testing array_column() function with int as first parameter --\n";
  27
+var_dump(array_column(1, 'foo'));
  28
+
  29
+echo "\n-- Testing array_column() key parameter should be a string or an integer (testing bool) --\n";
  30
+var_dump(array_column(array(), true));
  31
+
  32
+echo "\n-- Testing array_column() key parameter should be a string or integer (testing float) --\n";
  33
+var_dump(array_column(array(), 2.3));
  34
+
  35
+echo "\n-- Testing array_column() key parameter should be a string or integer (testing array) --\n";
  36
+var_dump(array_column(array(), array()));
  37
+
  38
+echo "Done\n";
  39
+?>
  40
+--EXPECTF--
  41
+*** Testing array_column() : error conditions ***
  42
+
  43
+-- Testing array_column() function with Zero arguments --
  44
+
  45
+Warning: array_column() expects exactly 2 parameters, 0 given in %s on line %d
  46
+NULL
  47
+
  48
+-- Testing array_column() function with One argument --
  49
+
  50
+Warning: array_column() expects exactly 2 parameters, 1 given in %s on line %d
  51
+NULL
  52
+
  53
+-- Testing array_column() function with more than expected no. of arguments --
  54
+
  55
+Warning: array_column() expects exactly 2 parameters, 3 given in %s on line %d
  56
+NULL
  57
+
  58
+-- Testing array_column() function with string as first parameter --
  59
+
  60
+Warning: array_column() expects parameter 1 to be array, string given in %s on line %d
  61
+NULL
  62
+
  63
+-- Testing array_column() function with int as first parameter --
  64
+
  65
+Warning: array_column() expects parameter 1 to be array, integer given in %s on line %d
  66
+NULL
  67
+
  68
+-- Testing array_column() key parameter should be a string or an integer (testing bool) --
  69
+
  70
+Warning: array_column(): The key should be either a string or an integer in %s on line %d
  71
+bool(false)
  72
+
  73
+-- Testing array_column() key parameter should be a string or integer (testing float) --
  74
+
  75
+Warning: array_column(): The key should be either a string or an integer in %s on line %d
  76
+bool(false)
  77
+
  78
+-- Testing array_column() key parameter should be a string or integer (testing array) --
  79
+
  80
+Warning: array_column(): The key should be either a string or an integer in %s on line %d
  81
+bool(false)
  82
+Done
Commit_comment_tip

Tip: You can add notes to lines in a file. Hover to the left of a line to make a note

Something went wrong with that request. Please try again.