Home > Software design >  How would I identify how many arguments are numerals using variable length parameters in PHP
How would I identify how many arguments are numerals using variable length parameters in PHP

Time:08-03

I am teaching myself php and I came across these variable length functions included in PHP. They are three being

  • func_get_args ()
  • func_num_args ()
  • func_get_arg ($i)

I understand how to use them so far, I would like to know how divide the arguments or arrays to know which ones are strings and which are numerical. for example

$data = funcArgSort('red', 'green', 21, 'blue', 67);

CodePudding user response:

One you get the list of args you can use array_filter() to pull out the arguments that are int's and the ones that are strings.

You can use is_int() and is_string() respectively.

Then if you can merge them back into one array and sort before returning.

For example:

<?php

function funcArgSort() {
  $args = func_get_args();
  // this gets an array of numbers
  $nums = array_filter($args, fn ($x) => is_int($x));

  // this gets an array of strings
  $strings = array_filter($args, fn ($x) => is_string($x));

  // this merges the two arrays
  $merged = [...$nums, ...$strings];

  // Note that `sort` returns a boolean and mutates the array
  // so we don't want to return the result of `sort`
  sort($merged);

  return $merged;
}

var_dump(funcArgSort('c', 3, 'b', 2, 'a', 1));
// output: ['a', 'b', 'c', 1, 2, 3]

Another alternative would be to use a loop to iterate through each argument and build up a list of numbers and strings. In this way, you only have to loop through the list of arguments once (which may or may not be a performance issue for your needs).

<?php

function funcArgSort() {
  $args = func_get_args();
  $nums = [];
  $strings = [];
  
  // Loop through each argument
  foreach($args as $arg) {
    // If it's a number, push it onto the nums array
    if (is_int($arg)) $nums[] = $arg;
    // If it's a string, push it onto the strings array
    if (is_string($arg)) $strings[] = $arg;
  }

  $merged = [...$strings, ...$nums];

  sort($merged);

  return $merged;
}

var_dump(funcArgSort('c', 3, 'b', 2, 'a', 1));
// output: ['a', 'b', 'c', 1, 2, 3]

And another alternative, if your use-case is as contrived as the examples above you could just sort the args and it will work as such:

function funcArgSort() {
  $args = func_get_args();

  sort($args);

  return $args;
}

var_dump(funcArgSort('c', 3, 'b', 2, 'a', 1));
// output: ['a', 'b', 'c', 1, 2, 3]
  •  Tags:  
  • php
  • Related