Skip to content

EFTEC/ArrayOne

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

34 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ArrayOne

It is a minimalist library that process arrays in PHP with no dependency.

This library is focused to work with business data(reading/saving files, database records, API, etc.), so it is not similar to Numpy, Pandas, NumPHP or alike because they target difference objectives. It is more closely similar to Microsoft PowerQuery and Linq. What it does? Filter, order, renaming column, grouping, validating, amongst many other operations.

  • it works with PHP arrays. PHP arrays allows hierarchy structures using indexed and/or associative values.
  • It is aimed at speed.
  • It is minimalist, using the minimum of dependencies and only 1 PHP class. Do you hate when a simple library adds a whole framework as dependency? Well, not here.
  • It works using fluent/nested notations.
  • Every method is documented using PhpDoc.

Packagist Total Downloads Maintenance composer php php CocoaPods

Basic examples

// Reducing an array using aggregate functions:
$invoice=[
    'id'=>1,
    'date'=>new DateTime('now'),
    'customer'=>10,
    'detail'=>[
        ['idproduct'=>1,'unitPrice'=>200,'quantity'=>3],
        ['idproduct'=>2,'unitPrice'=>300,'quantity'=>4],
        ['idproduct'=>3,'unitPrice'=>300,'quantity'=>5],
    ]
];
$arr=ArrayOne::set($invoice['detail'])
    ->reduce(['unitPrice'=>'sum','quantity'=>'sum'])
    ->all(); //['unitPrice'=>800,'quanty'=>12]
// or also
$arr=(new ArrayOne($invoice['detail']))
    ->reduce(['unitPrice'=>'sum','quantity'=>'sum'])
    ->all(); //['unitPrice'=>800,'quanty'=>12]

Getting started

First, you must install the library. You can download this library or use Composer for its installation:

composer require eftec/arrayone

Once the library is installed and included, you can use as:

use eftec\ArrayOne;
ArrayOne::set($array); // Initial operator: $array is our initial array.
    ->someoperator1()  // Middle operator: here we do one or many operations to transform the array
    ->someoperator2()
    ->someoperator3()
    ->all(); // End operator: and we get the end result that usually is an array but it could be even a literal.

Concepts

$array=['hello'  // indexed field
       'field2'=>'world', // named field
       'fields'=>[   // a field with sub-fields
           'alpha'=>1,
           'beta'=>2
       ],
       'table'=>[ // a field with a list of values (a table)
           ['id'=>1,'name'=>'red'],
           ['id'=>2,'name'=>'orange'],
           ['id'=>3,'name'=>'blue'],           
       ]
   ];
  • indexed and named fields works similarly.
  • Sometimes, some field contains an array of values that behave like a table (see table field)

Class ArrayOne

Class ArrayOne

Method __construct()

Constructor
You can use (new ArrayOne($array))->method() or use ArrayOne::set($array)->method();

Parameters:

  • $array param array|null $array (array|null)

Method isIndexArray()

Returns true if the array is an indexed array. It does not scan the whole array, but instead it only returns true if the index 0 exists, and it is the first value.
Example:

ArrayOne::isIndexArray(['cocacola','fanta']); // true
ArrayOne::isIndexArray(['prod1'=>'cocacola','prod2'=>'fanta']); // false (associative array)
ArrayOne::isIndexArray('cocacola'); // false (not array)

Parameters:

  • $value the value to analize. (mixed)

Method isIndexTableArray()

It returns true if the value is an indexed array with the first value an array (i.e. a table) Example:

ArrayOne::isIndexTableArray([['cocacola','fanta']]); // true
ArrayOne::isIndexTableArray(['cocacola','fanta']); // false
ArrayOne::isIndexTableArray(['first'=>['hello'],'second'=>'world']) // false

Parameters:

  • $value param mixed $value (mixed)

Method makeRequestArrayByExample()

It creates an associative array that could be used to be used by setRequest()
Example:

$this->makeRequestArrayByExample(['a'=1,'b'=>2]); // ['a'='post','b'=>'post'];

Parameters:

  • $array An associative array with some values. (array)
  • $type =['get','post','request','header','cookie'][$i] The default type (string)

Method makeValidateArrayByExample()

It generates a validate-array using an example array. It could be used by validation() and filter()
Example:

$this->makeValidateArrayByExample(['1','a','f'=>3.3]); // ['int','string','f'=>'float'];

Parameters:

  • $array param array $array (array)

Method makeWalk()

We call a method for every element of the array recursively.
Example:

ArrayOne::makeWalk(['a'=>'hello','b'=>['c'=>'world'],function($row,$id) { return strotupper($row);});

Parameters:

  • $array Our initial array (array)
  • $method the method to call, example: function($row,$index) { return $row; } (callable)
  • $identifyTable (def: false) if we want the array identify inside arrays as table (bool)

Method set()

It sets the array to be transformed, and it starts the pipeline
It must be the first operator unless you are using the constructor. Example:

ArrayOne::set($array)->all();
ArrayOne::set($array,$object)->all(); // the object is used by validate()
ArrayOne::set($array,SomeClass:class)->all(); // the object is used by validate()

Parameters:

  • $array param array|null $array (array|null)
  • $service the service instance. You can use the class or an object. (object|null|string)

Method setCsv()

It sets the array using a csv. This csv must have a header.
Example:

ArrayOne::setCsv("a,b,c\n1,2,3\n4,5,6")->all();

Parameters:

  • $string the string to parse (string)
  • $separator default ",". Set the field delimiter (one character only). (string)
  • $enclosure default '"'. Set the field enclosure character (one character only). (string)
  • $escape default "\". Set the escape character (one character only). (string)

Method setCsvHeadLess()

It sets the array using a head-less csv.
Example:

ArrayOne::setCsvHeadLess("1,2,3\n4,5,6")->all();
ArrayOne::setCsvHeadLess("1,2,3\n4,5,6",['c1','c2','c3'])->all();

Parameters:

  • $string the string to parse (string)
  • $header If the header is null, then it creates an indexed array.
    if the header is an array, then it is used as header (array|null)
  • $separator default ",". Set the field delimiter (one character only). (string)
  • $enclosure default '"'. Set the field enclosure character (one character only). (string)
  • $escape default "\". Set the escape character (one character only). (string)

Method setJson()

It sets the array using a json. Example:

ArrayOne::setJson('{"a":3,"b":[1,2,3]}')->all();

Parameters:

  • $json param string $json (string)

Method setRequest()

It sets the initial array readint the values from the request (get/post/header/etc.)
Example:

ArrayOne::setRequest([
'id'=>'get', // $_GET['id'] if not found then it uses the default value (null)
'name'=>'post|default', // $_POST['name'], if not found then it uses "default"
'content'=>'body' // it reads from the POST body
],null); // null is the default value if not other default value is set.

Parameters:

  • $fields An associative array when the values to read 'id'=>'type;defaultvalue'. Types:
    get: get it from the query string
    post: get it from the post
    header: get if from the header
    request: get if from the post, otherwise from get
    cookie: get if from the cookies
    body: get if from the post body (values are not serialized)
    verb: get if from the request method (GET/POST/PUT,etc.)
    (array)
  • $defaultValueAll the default value if the value is not found and not other default value is set. (mixed)
  • $separator Def:'.', The separator character used when the field is nested.
    example using '.' as separator html:
    result obtained:$result['a']['b']='hello'; (?string)

Method aggr()

Returns the aggregates value of a column
Example:

$sum=$this->set($arr)->aggr('sum','col'); // returns sum of the column 'col'
$min=$this->set($arr)->aggr('min','col'); // returns the min value of the column 'col'

Parameters:

  • $type =['max','min','avg','count','sum'][$i] (string)
  • $colName the column to aggregate (count does not require a column) (?mixed)
  • $getKey if false (default), it returns the value obtained. if true, it returns the key. (bool)

Method all()

Returns the whole array transformed and not only the current navigation.
Example:

$this->set($array)->nav('field')->all();

Method avg()

Returns the average value of a specific column
Example:

$max=$this->set($arr)->avg('col'); // returns the average of the column 'col'

Parameters:

  • $colName the column (mixed)

Method col()

Returns a single column as an array of values.
Example:

$this->col('c1'); // [['c1'=>1,'c2'=>2],['c1'=>3,'c2'=>4]] => [['c1'=>1],['c1'=>3]];

Parameters:

  • $colName the name of the column (mixed)

Method colRename()

It renames a column (or multiples columns) with a different name.
Example:

$this->colRename('c1','n1'); // [['c1'=1,'c2'=>2]] => [['n1'=>1,'c2'=2]]
$this->colRename(['c1','c2'],['n1','n2']); // [['c1'=1,'c2'=>2]] => [['n1'=>1,'n2'=2]]

Parameters:

  • $colName the name of the column or columns (string|array)
  • $newColName the name of the column or columns (string|array)

Method columnToIndex()

it converts a column into an index
Example:

$this->indexToField('colold'); //  [['colold'=>'a','col1'=>'b','col2'=>'c'] => ['a'=>['col1'=>'b','col2'=>'c']]

Parameters:

  • $oldColumn the old column. This column will be converted into an index (mixed)

Method count()

Returns the count of an array
Example:

$max=$this->set($arr)->count(); // returns the count (number of elements)

Method filter()

It filters the values. If the condition is false, then the row is deleted. It uses array_filter()
The indexes are not rebuilt.
Example:

$array = [['id' => 1, 'name' => 'chile'], ['id' => 2, 'name' => 'argentina'], ['id' => 3, 'name' => 'peru']];
// get the row #2 "argentina":
// using a function:
$r = ArrayOne::set($array)->filter(function($row, $id) {return $row['id'] === 2;}, true)->result();
$r = ArrayOne::set($array)->filter(fn($row, $id) => $row['id'] === 2, true)->result();
// using a function a returning a flat result:
$r = ArrayOne::set($array)->filter(function($row, $id) {return $row['id'] === 2;}, false)->result();
// using an associative array:
$r = ArrayOne::set($array)->filter(['id'=>'eq;2'], false)->result(); // 'eq;2' or simply '2'
// using an associative array that contains an array:
$r = ArrayOne::set($array)->filter(['id'=>['eq',2]], false)->result();
// multiples conditions: id=2 and col=10
$r = ArrayOne::set($array)->filter([['id'=>'eq;2'],['col','eq;10]], false)->result();

Parameters:

  • $condition you can use a callable function ($row,$id):true {}
    or a comparison array ['id'=>'eq;2|lt;3'] "|" adds more comparisons
    or a comparison array [['id=>['eq',2]],['id'=>['lt',3]]]
    (callable|null|array)
  • $flat param bool $flat (bool)

Method find()

It returns an array with the key and values of the elements that matches the condition.
Example:

ArrayOne::set($array)->find(function($row, $id) {
return $row['id'] === 2;
})->all(); // [[0,"apple"],[3,"pear"]]

Parameters:

  • $condition you can use a callable function ($row,$id):bool {}
    or a comparison array ['id'=>'eq;2|lt;3'] "|" adds more comparisons
    or a comparison array [['id=>['eq',2]],['id'=>['lt',3]]]
    (callable|null|array)
  • $onlyFirst if true then it only returns the first value (bool)
  • $mode =['all','key','value'] // (default is all)
    all returns the key and the value obtained
    key only returns the key
    value only returns the value (string)

Method first()

It returns the first element of an array.

Method flat()

It flats the results. If the result is an array with a single row, then it returns the row without the array
Example:

$this->flat(); // [['a'=>1,'b'=>2]] => ['a'=>1,'b'=>2]

Method getAll()

Clone of a(). This method returns the whole array transformed and not only the current navigation.
Example:

$this->set($array)->nav('field')->getAll();

Method getVersion()

It gets the current version of the library

Method group()

It groups one column and return its column grouped and values aggregated
Example:

// group in the same column using a predefined function:
$this->group('type',['c1'=>'sum','price'=>'sum']); // ['type1'=>['c1'=>20,'price'=>30]]
// group in a different column using a predefined function:
$this->group('type',['newcol'=>'sum(amount)','price'=>'sum(price)']);
// multiples columns (columns are jointed using $this->separator)
$this->group(['col1,col2'],['col3'=>'sum']);
// group using an indexed index:
$this->group('type',['c1'=>'sum','pri'=>'sum','grp'=>'group'],false); // [['c1'=>20,'pri'=>30,'grp'=>'type1']]
// group using a function:
$this->group('type',['c1'=>function($cumulate,$row) { return $cumulate+$row['c1'];}]);
// group using two functions, one per every row and the other at the end:
$this->group('type',['c1'=>[
function($cumulate,$row) { return $cumulate+$row['c1'];},
function($cumulate,$numrows) { return $cumulate/$numRows;}]); // obtain the average of c1

Parameters:

  • $columnToGroup the column (or columns) to group. (mixed)
  • $funcAggreg An associative array ['col-to-aggregate'=>'aggregation']
    or ['new-col'=>'aggregation(col-to-agregate)']
    or ['col-to-aggr'=>function($cumulate,$row) {}]
    or ['col-to-aggr'=>[function($cumulate,$row){},function($cumulate,$numRows){}]
    stack: It stack the rows grouped by the column
    count: Count
    avg: Average
    min: Minimum
    max: Maximum
    sum: Sum
    first: First
    last: last
    group: The grouped value
    function:$cumulate: Is where the value will be accumulated, initially is null
    function:$row: The current value of the row
    (array)
  • $useGroupIndex (def true), if true, then the result will use the grouped value as index
    if false, then the result will return the values as an indexed array. (bool)

Method indexToCol()

It converts the index into a column, and converts the array into an indexed array
Example:

$this->indexToCol('colnew'); // ['a'=>['col1'=>'b','col2'=>'c']] => [['colnew'=>'a','col1'=>'b','col2'=>'c']

Parameters:

  • $newColumn the name of the new column (mixed)

Method isIndex()

It is the dynamic version of the method isIndexArray.

Method isIndexTable()

The dynamic version of the method isIndexTableArray()

Method isValid()

Method join()

Joins the current array with another array
If the columns of both arrays have the same name, then the current name is retained.
Example:

$products=[['id'=>1,'name'=>'cocacola','idtype'=>123]];
$types=[['id'=>123,'desc'=>'it is the type #123']];
ArrayOne::set($products)->join($types,'idtype','id')->all()
// [['id'=>1,'prod'=>'cocacola','idtype'=>123,'desc'=>'it is the type #123']] "id" is from product.

Parameters:

  • $arrayToJoin param array|null $arrayToJoin (array|null)
  • $column1 the column of the current array (mixed)
  • $column2 the column of the array to join. (mixed)

Method keepCol()

It keeps a column or columns and removes the rest of columns
Example:

$this->keepCol('col1');
$this->keepCol(['col1','col2']);

Parameters:

  • $colName The name of the column or columns (array) (mixed)

Method last()

It returns the last element of an array.

Method map()

It calls a function for every element of an array
Example:

$this->map(function($row) { return strtoupper($row); });
$this->map(function($row,$index) {$row['col1']=$row['col2']*$row['col3']; return $row });
$this->modCol('col1',function($row,$index) { return $row['col2']*$row['col3'];  }); // it does the same

Parameters:

  • $condition The function to call.
    It must have an argument (the current row) and it must return a value (callable|null)

Method mask()

It masks the current array using another array.
Masking deletes all field that are not part of our mask
The mask is smart to recognize a table, so it could mask multiples values by only specifying the first row.
Example:

$array=['a'=>1,'b'=>2,'c'=>3,'items'=>[[a1'=>1,'a2'=>2,'a3'=3],[a1'=>1,'a2'=>2,'a3'=3]];
$mask=['a'=>1,'items'=>[[a1'=>1]]; // [[a1'=>1]] masks an entire table
$this->mask($mask); // $array=['a'=>1,'items'=>[[a1'=>1],[a1'=>1]];

Parameters:

  • $arrayMask An associative array with the mask. The mask could contain any value. (array)

Method max()

Returns the max of a specific column
Example:

$max=$this->set($arr)->max('col'); // returns the max value of the column 'col'
$max=$this->set($arr)->max('col',true); // returns the key where is the max value

Parameters:

  • $colName the column (mixed)
  • $getKey param bool $getKey (bool)

Method min()

Returns the min of a specific column
Example:

$max=$this->set($arr)->min('col'); // returns the min value of the column 'col'
$max=$this->set($arr)->min('col',true); // returns the key where is the min value

Parameters:

  • $colName the column (mixed)
  • $getKey param bool $getKey (bool)

Method minRow()

It finds the minimum value of a specific column and returns one or many values
Example:

$max=$this->set($arr)->minRow('col'); // returns the min row of the column 'col'
$max=$this->set($arr)->minRow('col','all'); // returns min max values (rows)
$max=$this->set($arr)->minRow('col','all',true); // returns min max values (indexes)

Parameters:

  • $colName the name of the column to find a value (mixed)
  • $returnType =['first','last','random','all'][$i]
    • first returns the first min value
    • last returns the last min value
    • random if there are many min values, then it returns one randomly
    • all returns all the values that have the min value (string)
  • $getKey (default is false) if it returns the keys(indexs). If false it returns the columns (bool)

Method maxRow()

It finds the minimum value of a specific column and returns one or many values
Example:

$max=$this->set($arr)->maxRow('col'); // returns the max row of the column 'col'
$max=$this->set($arr)->maxRow('col','all'); // returns all max values (rows)
$max=$this->set($arr)->maxRow('col','all',true); // returns all max values (indexes)

Parameters:

  • $colName the name of the column to find a value (mixed)
  • $returnType =['first','last','random','all'][$i]
    • first returns the first min value
    • last returns the last min value
    • random if there are many min values, then it returns one randomly
    • all returns all the values that have the min value (string)
  • $getKey (default is false) if it returns the keys(indexs). If false it returns the columns (bool)

Method modCol()

It adds or modify a column. Example:

$this->modCol('col1',function($row,$index) { return $row['col2']*$row['col3'];  });
$this->map(function($row,$index) {$row['col1']=$row['col2']*$row['col3']; return $row }); // it does the same

Parameters:

  • $colName the name of the column. If null, then it uses the entire row (string|int|null)
  • $operation the operation to realize. (callable|null)

Method nPos()

It returns the n-position of an array.

Parameters:

  • $index param $index ()

Method offsetExists()

Method offsetGet()

It gets a value of the array
Example:

$this->offsetGet(1); // $this->array[1];

Parameters:

  • $offset (if null, then it used the entire array) (mixed|null)

Method offsetSet()

It sets the value of the array.
Example:

$this->offsetSet(1,"hello"); // $this->array[1]="hello";

Parameters:

  • $offset (if null, then it used the entire array) (mixed|null)
  • $value the value to set (mixed)

Method offsetUnset()

It deletes a row of the array.
Example:

$this->offsetUnset(1); // unset($this->array[1]);

Parameters:

  • $offset (if null, then it used the entire array) (mixed|null)

Method reduce()

You can reduce (flat) an array using aggregations or a custom function. Example:

$this->reduce(['col1'=>'sum','col2'=>'avg','col3'=>'min','col4'=>'max']);
$this->reduce(function($row,$index,$prev) { return ['col1'=>$row['col1']+$prev['col1]];  });

Parameters:

  • $functionAggregation An associative array where the index is the column and the value is the function of aggregation
    A function using the syntax: function ($row,$index,$prev) where $prev is the accumulator value (array|callable)

Method removeCol()

It removes a column or columns
Example:

$this->removeCol('col1');
$this->removeCol(['col1','col2']);

Parameters:

  • $colName The name of the column or columns (array) (mixed)

Method removeDuplicate()

This function removes duplicates of a table.
Example:

$dup=$this->removeDuplicate('col');
$dup=$this->removeDuplicate(['col1','col2']);

Parameters:

  • $colName the column (or columns) to use to remove duplicates. (array|string)

Method removeFirstRow()

It removes the first row or rows. Numeric index could be renumbered. Example:

$this->removeFirstRow(); // remove the first row
$this->removeFirstRow(3); // remove the first 3 rows

Parameters:

  • $numberOfRows The number of rows to delete, the default is 1 (the first row) (int)
  • $renumber if true then it renumber the list
    ex: if 1 is deleted then $renumber=true: [0=>0,1=>1,'x'=>2] => [0=>0,1=>2]
    ex: if 1 is deleted then $renumber=false: [0=>0,1=>1,2=>2] => [0=>0,2=>2]
    (bool)

Method removeLastRow()

It removes the last row or rows Example:

$this->removeLastRow(3);

Parameters:

  • $numberOfRows the number of rows to delete (int)
  • $renumber if true then it renumber the list (since we are deleting the last value then usually we don't need it
    ex: if 1 is deleted then $renumber=true: [0=>0,1=>1,2=>2] => [0=>0,1=>2]
    ex: if 1 is deleted then $renumber=false: [0=>0,1=>1,2=>2] => [0=>0,2=>2]
    (bool)

Method removeRow()

It removes the row with the id $rowId. If the row does not exist, then it does nothing Example:

$this->removeRow(20);

Parameters:

  • $rowId The id of the row to delete (mixed)
  • $renumber if true then it renumber the list
    ex: if 1 is deleted then $renumber=true: [0=>0,1=>1,2=>2] => [0=>0,1=>2]
    ex: if 1 is deleted then $renumber=false: [0=>0,1=>1,2=>2] => [0=>0,2=>2]
    (bool)

Method rowToValue()

It transforms a row of values into a single value. If a row does not contain a column then it returns null Example:

$values=[['a'=>1,'b'=>2'],['a'=>2,'b'=>3'],['c'=>4]];
$this->rowToValue('a'); // [1,2]
$this->rowToValue('a',true); // [1,2,null]

Parameters:

  • $colName The name of the column (mixed)
  • $nullWhenNotFound if true then it returns null when the column is not found in a row
    otherwise, it skips the column (bool)

Method shuffle()

Method sort()

Sort an array using a column or columns
Example:

$this->sort('payment','desc'); // sort an array using the column paypent descending.
$this->sort(['payment','customer']); // sort both columns ascending.
$this->sort(); // it sorts the array ascending using the column
$this->sort(['payment','customer'],['asc','desc']); // sorth both columns, ascending and descending
$this->sort(['payment','customer'],'desc'); // it sorts both columns descending.

Parameters:

  • $column The column or columns to sort.
    If column is null, then it sorts the row (instead of a column of the row) (mixed)
  • $direction =['asc','desc'][$i] ascending or descending.
    By default is ascending. (mixed)

Method splitColumn()

It split a column in two or more columns using a separator

Parameters:

  • $colName The column to split (string)
  • $newCols The name of the new columns (array)
  • $separator If null, then it uses the default separator ($this->separator) (string|null)

Method sum()

Returns the sum value of a specific column
Example:

$max=$this->set($arr)->sum('col'); // returns the sum of the column 'col'

Parameters:

  • $colName the column (mixed)

Method validate()

Validate the current array using a comparison table
It returns an associative array with null in the fields without error, or other value if error. Example:

$this->set($arr)
->validate([
'id'=>'int',
'table'=>[['col1'=>'int','col2'=>'string']],   // note the double [[ ]] to indicate a table of values
'list'=>[['int']]
])
->all();
// example using custom function
// 1) defining the service class.
class ServiceClass {
public function test($value,$compare=null,&$msg=null): bool
{
return true;
}
}
// 2.1) and setting the service class using the class
ValidateOne
->set($array,ServiceClass:class)
->validate('field'=>'fn:test') // or ->validate('field'=>[['fn','test']])
->all();
// 2.2) or you could use an instance
$obj=new ServiceClass();
ValidateOne
->set($array,$obj)
->validate('field'=>'fn:test') // or ->validate('field'=>[['fn','test']])
->all();
condition description example work example fail expression
not negates any comparison, excepting nullable and custom functions. Example: "notint" "hello" 20 notint
nullable the value CAN be a null. **If the value is null, then it ignores other validations** null nullable
f: It calls a custom function defined in the service class. See example "hello" f:test
contain like if a text is contained in "helloworld" "hello" contain;world
alpha if the value is alphabetic "hello" "hello33" alpha
alphanumunder if the value is alphanumeric or under-case "hello_33" "hello!33" alphanumunder
alphanum if the value is alphanumeric "hello33" "hello!33" alphanum
text if the value is a text "hello" true text
regexp if the value match a regular expression. You can't use comma in the regular expression. "abc123" "xyz123" regexp;
email if the value is an email "[email protected]" "aaa.bbb.com" email
url if the value is an url [https://www.nic.cl] (https://www.nic.cl/) "aaaa" url
domain if the value is a domain [www.nic.cl] (www.nic.cl) "….." domain
minlen the value must have a minimum length "hello" "h" minlen;3
maxlen the value must have a maximum lenght "h" "hello" maxlen;3
betweenlen if the value has a size between "hello" "h" betweenlen;4,5
exist if the value exists "hi" null exist
missing if the value not exist null "hi" missing
req,required if the value is required "hi" null req,required
eq == if the value is equals to 1 0 eq;1
ne != <> if the value is not equals to 1 0 ne;0
null The value MUST be null. It is different to nullable because nullable is a "CAN" null null
empty if the value is empty "" "hello" empty
lt if the value is less than 1 10 lt;5
lte/le if the value is less or equals than 1 10 lte;5
gt if the value is great than 10 1 gt;5
gte/ge if the value is great or equals than 10 1 gte;5
between if the value is between 5 0 between;4,5
true if the value is true or 1 true false true
false if the value is false, or 0 false true false
array if the value is an array [1,2,3] 1 array
int if the value is an integer 1 "hello" int
string if the value is a string "hello" true string
float if the value is a float 333.3 "hello" float
object if the value is an object new stdClass() 1 object
in the value must be in a list

Parameters:

  • $comparisonTable see table (array)
  • $extraFieldError if true and the current array has more values than comparison table, then it returns an error. (bool)

versions

  • 2.6.1 2024-09-28
    • [fixed]
      • In 2.6 and lower, many functions detected when the array is null to avoid to do the operation.
      • In 2.6.1, many functions detects when the array is empty (including null) to avoid to do the operation.
  • 2.6 2024-09-26
    • [new] minRow()
    • [new] maxRow()
  • 2.5.1 2024-09-20
    • [new] keepCol()
    • [new] coolRename()
    • [new] shuffle()
    • [new] updated this file to contain all the definitions.
  • 2.4 2024-08-15
    • [update] sort() now allow to group by multiples columns
    • [fixed] group() fixed the value returned. If multiples columns are used then, the new grouping column could be split.
    • [new] splitColumn() split a column in two or more columns.~~
  • 2.3 2024-08-10
    • [new] sum(),min(),max(),avg(),count(),aggr()
  • 2.2 2024-08-06
    • sort() now accepts multiple columns.
  • 2.1 2024-08-03
    • removeDuplicate(),group() now accepts multiples columns.
  • 2.00 2024-03-10
    • nav() and currentArray() are removed from 2.0. The library was optimized and streamlined, and those functions are redundant.
      migration:
// before:
$r=ArrayOne::set($array)->nav('field')->...->all();
// now:
$r=ArrayOne::set($array['field'])->...->all();
// before:
$r=ArrayOne::set($array)->nav('field')->...->currentArray();
// now:
$r=$array;
$r['field']=ArrayOne::set($array['field'])->...->all();
  • 1.12 2024-03-01
    • Updating dependency to PHP 7.4. The extended support of PHP 7.2 ended 3 years ago.
  • 1.11 2024-03-01
    • added method find()
    • aedded method isIndexArray() and isIndexTableArray()
    • now find() and filter() allows multiple conditions
    • and find() and filter(), the condition ['field'='eq;2'] could be written as ['field','2']
  • 1.10 2024-02-24
    • Added more doc for validate()
    • Now validate also returns an array $this::$errorStack
    • New method isValid() which returns true is validate has no error. Otherwise false.
  • 1.9 2023-11-13
    • added rowToValue()
  • 1.8.3 2023-09-16
    • offsetGet() generates a warning in php 8.1 (fixed)
    • current() is marked as deprecated (but it is still functional), use getCurrent()
  • 1.8.2 2023-09-16
    • solved a psr-4 problem in composer.json
  • 1.8.1 2023-09-16
    • change the PHPDOC comments, now it uses markdown instead of "pre" tag.
    • Added ArrayAccess interface.
  • 1.8 2023-07-29
    • [mod] group() allows to specify a custom function(s).
  • 1.7 2023-06-04
    • [new] group() allows returning the grouped value. It also allows returning the values as an indexed array.
  • 1.6 2023-04-10
    • [optimization] setCurrentArray() now is only used when nav() is called or when the value is returned.
  • 1.5 2023-04-07
    • [new] filtercondition() now allow conditions as array.
  • 1.4 2023-04-05
    • [fix] filtercondition() fixed a warning when the value is null.
    • [new] group() now allow to stack elements
    • [new] group() now allow to specify a new column
  • 1.3 2023-03-31
    • validation now allow negation ("not" prefix).
  • 1.2
    • renamed method getValidateArrayByExample() to makeValidateArrayByExample()
    • new method makeRequestArrayByExample()
    • new method setRequest()
    • rename method setCol() to modCol(). Methods that start with "set" are used to initialize the variable.
  • 1.1 2023-03-28
    • method filter() now allow a comparison array and a callable function.
    • new method getValidateArrayByExample()
    • new method removeRow()
    • new method removeFirstRow()
    • new mehtod removeLastRow()
    • new method setCsv()
    • new method setJson()
  • 1.0 2023-03-26 first version

License

Copyright Jorge Castro Castillo 2023-2024. Licensed under dual license: LGPL-3.0 and commercial license.

In short:

  • Can I use in a close source application for free? Yes if you don't modify this library.
  • If you modify it, then you must share the source code.
  • If you want to modify privately, then you must buy a license.