Is there more efficient way to index an array? PHP - php

I have no idea what keyword should I use on google to find the solution.
This is my code:
function getArray(){
return array('one','two','three');
}
$array = getArray();
echo $array[2];
My question is there a more efficient way to print the third element from the returned array?

If you want the easiest way to print the x-th element of the array, you should use a parameter in your function.
This way you can also do some checks to see if the index is valid.
function getArray($index){
$array = ['one', 'two', 'three'];
if ($index < 0 || $index >= count($array)) {
return null;
} else {
return $array[$index];
}
}
echo getArray(2);

Related

PHP In_MultiArray Function

on http://php.net/manual/en/function.in-array.php - if you scroll down it gives a function to determine if a string is inside of a query in a multidimensional array. "If you found yourself in need of a multidimensional array in_array like function you can use the one below. Works in a fair amount of time"
Here's original code(working):
function in_multiarray($elem, $array)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom] == $elem)
return true;
else
if(is_array($array[$bottom]))
if(in_multiarray($elem, ($array[$bottom])))
return true;
$bottom++;
}
return false;
}
What I'm trying to do is instead of returning 'true' or 'false' - i'd like to return the ROW #. So my initial thought was to simply replace 'return true' with 'return $bottom; however it isn't returning the record number.
Modified Function (not working);
function in_multiarray($elem, $array)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom] == $elem)
return $bottom;
else
if(is_array($array[$bottom]))
if(in_multiarray($elem, ($array[$bottom])))
return $bottom;
$bottom++;
}
return false;
}
Does anyone have an idea how to modify this function to return the ROW number that contains the match?
Here's a sample of the array...
$sample = array
array ("oldpage1.php","newpage1.php"),
array ("oldpage2.php","newpage2.php"),
array ("oldpage3.php","newpage3.php"),
array ("oldpage4.php","newpage4.php"),
array ("oldpage5.php","newpage5.php")
etc.
);
$row = in_multiarray($input, $sample);
Therefore if we know the row # we can fetch the new page with a simple
$newpage=$sample[$row][1]
Thanks!
It's worth noting that a function like in_array is intended to tell you whether or not a value exists inside of an array. What you're looking for seems to be a lot closer to something like array_search, which is designed to actually provide you with the key that points to a given value in the array.
However, because you're using a multi-dimensional array what you're actually looking for is the key that points to the array that contains the value. Hence we can divide and conquer this problem with two simple steps.
Map
Filter
The first step is to map a function in_array to every element in the first array (which is just another array). This will tell us which elements of the primary array contain an array that contains the value we're searching for.
$result = array_map(function($arr) use($search) {
return in_array($search, $arr, true);
}, $arr, [$searchValue]);
The second step is to then return the keys to those arrays (i.e. filter the result).
$keys = array_keys(array_filter($result));
Now you have all the keys of any matching items. If you want to apply as just one custom filter that specifies exactly where in the subarray to look, you could also do it like this.
$search = "oldpage2.php";
$sample = [
["oldpage1.php","newpage1.php"],
["oldpage2.php","newpage2.php"],
["oldpage3.php","newpage3.php"],
["oldpage4.php","newpage4.php"],
["oldpage5.php","newpage5.php"],
];
$keys = array_keys(array_filter($sample, function($arr) use($search) {
return $arr[0] === $search;
}));
var_dump($keys);
And you get...
array(1) {
[0]=>
int(1)
}
So now you know that "oldpage2.php" is in row 1 in $sample[1][0] which means you can do this to get the results out of the array.
foreach($keys as $key) {
echo "{$sample[$key][0]} maps to {$sample[$key][1]}\n";
}
Giving you
oldpage2.php maps to newpage2.php
If you want to return only the first result you could do that as well with a function like this using similar approach.
function getFirstMatch($search, Array $arr) {
foreach($arr as $key => $value) {
if ($value[0] === $search) {
return $value[1];
}
}
}
echo getFirstMatch("oldpage4.php", $sample); // newpage4.php
The Better Alternative
Of course, the better approach is to actually use the oldpage names as the actual keys of the array rather than do this expensive search through the array, because array lookup by key in PHP is just an O(1) operation, whereas this needle/haystack approach is O(N).
So we turn your $samples array into something like this and the search no longer requires any functions...
$samples = [
"oldpage1.php" => "newpage1.php",
"oldpage2.php" => "newpage2.php",
"oldpage3.php" => "newpage3.php",
"oldpage4.php" => "newpage4.php",
"oldpage5.php" => "newpage5.php",
];
Now you can just do something like $newpage = $samples[$search] and you get exactly what you're looking for. So echo $samples["oldpage2.php"] gives you "newpage2.php" directly without the intermediary step of searching through each array.
You can use the following code to get the full path to the value:
function in_multiarray($elem, $array, &$result)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom] == $elem) {
array_unshift($result, $bottom);
return true;
}
else {
if(is_array($array[$bottom])) {
if(in_multiarray($elem, $array[$bottom], $result)) {
array_unshift($result, $bottom);
return true;
}
}
}
$bottom++;
}
array_shift($result);
return false;
}
$sample = array(
array ("oldpage1.php","newpage1.php"),
array ("oldpage2.php","newpage2.php"),
array ("oldpage3.php","newpage3.php"),
array ("oldpage4.php","newpage4.php"),
array ("oldpage5.php","newpage5.php")
);
$input = "newpage5.php";
$result = [];
in_multiarray($input, $sample, $result);
print_r($result);
Path is stored in $result;

How to find item in array?

Being new to PHP and its arrays I wonder if there is a better way of doing a simple search like this:
$found = "0";
foreach ($myArray as $item) {
if ($item->id == "Foo") {
$found = $item->value;
break;
}
}
Another solution would be to use array_filter:
$matchingArray = array_filter($myArray, function($object) {
return $object->id == 'Foo';
});
It will iterate on your array, and call the provided callback (second parameter) with each element in your array. The callback needs to return true, if the item matches your needs, false otherwise.
If you only need the first one:
if(count($matchingArray) > 0){
$firstMatch = $matchingArray[0];
}else{
// none found.
}
You can use
array_search()
or you can simply use:
if(in_array($foo, $bar)
where $foo is a value to look for and $bar is an array

Test if one array is a subset of another

How can I determine if one array is a subset of another (all elements in the first are present in the second)?
$s1 = "string1>string2>string3>string4>string5>string6>";
$arr1 = explode(">", $s1);
$s2 = "string1>string4>string5";
$arr2 = explode(">", $s2);
$isSubset = /* ??? */
if (array_intersect($array1, $array2) == $array1) {
// $array1 is a subset of $array2
}
Simple: use array subtraction.
On array subtraction, you will know whether or not one array is a subset of the other.
Example:
if (!array_diff($array1, $array2)) {
// $array1 is a subset of $array2
}
Reference: array_diff
You can use array_intersect also.
Try that
If you start from strings, you could check strstr($fullString,$subsetStr);. But that'll only work when all chars have the same order: 'abcd','cd' will work, but 'abcd','ad' won't.
But instead of writing your own, custom, function you should know that PHP has TONS of array functions, so its neigh on impossible that there isn't a std function that can do what you need it to do. In this case, I'd suggest array_diff:
$srcString = explode('>','string1>string2>string3>string4>string5');
$subset = explode('>','string3>string2>string5');
$isSubset = array_diff($subset,$srcString);
//if (empty($isSubset)) --> cf comments: somewhat safer branch:
if (!$isSubset)
{
echo 'Subset';
return true;
}
else
{
echo 'Nope, substrings: '.implode(', ',$isSubset).' Didn\'t match';
return false;
}
I would create an associated array of the larger array, then iterate through the smaller array, looking for a non collision, if you find one, return false.
function isSubset($arr1,$arr2){
$map = Array();
for ($i=0;$i<count($arr1);$i++){
$map[$arr[$i]]=true;
}
for ($i=0;$i<count($arr2);$i++){
if (!isset($map[$arr2[$i]])){
return false;
}
}
return true;
$s1 = "1>2>3>4>5>6>7";
$arr1 = explode(">",$s1);
$s2 = "1>2>3";
$arr2 = explode(">",$s2);
if(isSub($arr1,$arr2)){
echo 'true';
}else{
echo 'false';
}
function isSub($a1,$a2){
$num2 = count($a2);
$sub = $num2;
for($i = 0;$i < $num2 ;$i++){
if(in_array($a2[$i],$a1)){
$sub--;
}
}
return ($sub==0)? true:false;
}
Simple function which will return true if array is exact subset otherwise false. Solution is applicable for two dimensional array as well.
function is_array_subset($superArr, $subArr) {
foreach ($subArr as $key => $value) {
//check if keys not set in super array OR values are unequal in both array.
if (!isset($superArr[$key]) || $superArr[$key] != $value) {
return false;
}
}
return true;
}

Removing array item by value [duplicate]

This question already has answers here:
PHP: How to remove specific element from an array?
(22 answers)
PHP array delete by value (not key)
(20 answers)
Closed 1 year ago.
I need to remove array item with given value:
if (in_array($id, $items)) {
$items = array_flip($items);
unset($items[ $id ]);
$items = array_flip($items);
}
Could it be done in shorter (more efficient) way?
It can be accomplished with a simple one-liner.
Having this array:
$arr = array('nice_item', 'remove_me', 'another_liked_item', 'remove_me_also');
You can do:
$arr = array_diff($arr, array('remove_me', 'remove_me_also'));
And the value of $arr will be:
array('nice_item', 'another_liked_item')
I am adding a second answer. I wrote a quick benchmarking script to try various methods here.
$arr = array(0 => 123456);
for($i = 1; $i < 500000; $i++) {
$arr[$i] = rand(0,PHP_INT_MAX);
}
shuffle($arr);
$arr2 = $arr;
$arr3 = $arr;
/**
* Method 1 - array_search()
*/
$start = microtime(true);
while(($key = array_search(123456,$arr)) !== false) {
unset($arr[$key]);
}
echo count($arr). ' left, in '.(microtime(true) - $start).' seconds<BR>';
/**
* Method 2 - basic loop
*/
$start = microtime(true);
foreach($arr2 as $k => $v) {
if ($v == 123456) {
unset($arr2[$k]);
}
}
echo count($arr2). 'left, in '.(microtime(true) - $start).' seconds<BR>';
/**
* Method 3 - array_keys() with search parameter
*/
$start = microtime(true);
$keys = array_keys($arr3,123456);
foreach($keys as $k) {
unset($arr3[$k]);
}
echo count($arr3). 'left, in '.(microtime(true) - $start).' seconds<BR>';
The third method, array_keys() with the optional search parameter specified, seems to be by far the best method. Output example:
499999 left, in 0.090957164764404 seconds
499999left, in 0.43156313896179 seconds
499999left, in 0.028877019882202 seconds
Judging by this, the solution I would use then would be:
$keysToRemove = array_keys($items,$id);
foreach($keysToRemove as $k) {
unset($items[$k]);
}
How about:
if (($key = array_search($id, $items)) !== false) unset($items[$key]);
or for multiple values:
while(($key = array_search($id, $items)) !== false) {
unset($items[$key]);
}
This would prevent key loss as well, which is a side effect of array_flip().
to remove $rm_val from $arr
unset($arr[array_search($rm_val, $arr)]);
The most powerful solution would be using array_filter, which allows you to define your own filtering function.
But some might say it's a bit overkill, in your situation...
A simple foreach loop to go trough the array and remove the item you don't want should be enough.
Something like this, in your case, should probably do the trick :
foreach ($items as $key => $value) {
if ($value == $id) {
unset($items[$key]);
// If you know you only have one line to remove, you can decomment the next line, to stop looping
//break;
}
}
Try array_search()
Your solutions only work if you have unique values in your array
See:
<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
?>
A better way would be unset with array_search, in a loop if neccessary.
w/o flip:
<?php
foreach ($items as $key => $value) {
if ($id === $value) {
unset($items[$key]);
}
}
function deleteValyeFromArray($array,$value)
{
foreach($array as $key=>$val)
{
if($val == $value)
{
unset($array[$key]);
}
}
return $array;
}
You can use array_splice function for this operation Ref : array_splice
array_splice($array, array_search(58, $array ), 1);

Checking if array is multidimensional or not?

What is the most efficient way to check if an array is a flat array
of primitive values or if it is a multidimensional array?
Is there any way to do this without actually looping through an
array and running is_array() on each of its elements?
Use count() twice; one time in default mode and one time in recursive mode. If the values match, the array is not multidimensional, as a multidimensional array would have a higher recursive count.
if (count($array) == count($array, COUNT_RECURSIVE))
{
echo 'array is not multidimensional';
}
else
{
echo 'array is multidimensional';
}
This option second value mode was added in PHP 4.2.0. From the PHP Docs:
If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array. count() does not detect infinite recursion.
However this method does not detect array(array()).
The short answer is no you can't do it without at least looping implicitly if the 'second dimension' could be anywhere. If it has to be in the first item, you'd just do
is_array($arr[0]);
But, the most efficient general way I could find is to use a foreach loop on the array, shortcircuiting whenever a hit is found (at least the implicit loop is better than the straight for()):
$ more multi.php
<?php
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
$c = array(1 => 'a',2 => 'b','foo' => array(1,array(2)));
function is_multi($a) {
$rv = array_filter($a,'is_array');
if(count($rv)>0) return true;
return false;
}
function is_multi2($a) {
foreach ($a as $v) {
if (is_array($v)) return true;
}
return false;
}
function is_multi3($a) {
$c = count($a);
for ($i=0;$i<$c;$i++) {
if (is_array($a[$i])) return true;
}
return false;
}
$iters = 500000;
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi($a);
is_multi($b);
is_multi($c);
}
$end = microtime(true);
echo "is_multi took ".($end-$time)." seconds in $iters times\n";
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi2($a);
is_multi2($b);
is_multi2($c);
}
$end = microtime(true);
echo "is_multi2 took ".($end-$time)." seconds in $iters times\n";
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi3($a);
is_multi3($b);
is_multi3($c);
}
$end = microtime(true);
echo "is_multi3 took ".($end-$time)." seconds in $iters times\n";
?>
$ php multi.php
is_multi took 7.53565130424 seconds in 500000 times
is_multi2 took 4.56964588165 seconds in 500000 times
is_multi3 took 9.01706600189 seconds in 500000 times
Implicit looping, but we can't shortcircuit as soon as a match is found...
$ more multi.php
<?php
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
function is_multi($a) {
$rv = array_filter($a,'is_array');
if(count($rv)>0) return true;
return false;
}
var_dump(is_multi($a));
var_dump(is_multi($b));
?>
$ php multi.php
bool(true)
bool(false)
For PHP 4.2.0 or newer:
function is_multi($array) {
return (count($array) != count($array, 1));
}
I think this is the most straight forward way and it's state-of-the-art:
function is_multidimensional(array $array) {
return count($array) !== count($array, COUNT_RECURSIVE);
}
After PHP 7 you could simply do:
public function is_multi(array $array):bool
{
return is_array($array[array_key_first($array)]);
}
You could look check is_array() on the first element, under the assumption that if the first element of an array is an array, then the rest of them are too.
I think you will find that this function is the simplest, most efficient, and fastest way.
function isMultiArray($a){
foreach($a as $v) if(is_array($v)) return TRUE;
return FALSE;
}
You can test it like this:
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
echo isMultiArray($a) ? 'is multi':'is not multi';
echo '<br />';
echo isMultiArray($b) ? 'is multi':'is not multi';
Don't use COUNT_RECURSIVE
click this site for know why
use rsort and then use isset
function is_multi_array( $arr ) {
rsort( $arr );
return isset( $arr[0] ) && is_array( $arr[0] );
}
//Usage
var_dump( is_multi_array( $some_array ) );
Even this works
is_array(current($array));
If false its a single dimension array if true its a multi dimension array.
current will give you the first element of your array and check if the first element is an array or not by is_array function.
You can also do a simple check like this:
$array = array('yo'=>'dream', 'mydear'=> array('anotherYo'=>'dream'));
$array1 = array('yo'=>'dream', 'mydear'=> 'not_array');
function is_multi_dimensional($array){
$flag = 0;
while(list($k,$value)=each($array)){
if(is_array($value))
$flag = 1;
}
return $flag;
}
echo is_multi_dimensional($array); // returns 1
echo is_multi_dimensional($array1); // returns 0
I think this one is classy (props to another user I don't know his username):
static public function isMulti($array)
{
$result = array_unique(array_map("gettype",$array));
return count($result) == 1 && array_shift($result) == "array";
}
In my case. I stuck in vary strange condition.
1st case = array("data"=> "name");
2nd case = array("data"=> array("name"=>"username","fname"=>"fname"));
But if data has array instead of value then sizeof() or count() function not work for this condition. Then i create custom function to check.
If first index of array have value then it return "only value"
But if index have array instead of value then it return "has array"
I use this way
function is_multi($a) {
foreach ($a as $v) {
if (is_array($v))
{
return "has array";
break;
}
break;
}
return 'only value';
}
Special thanks to Vinko Vrsalovic
Its as simple as
$isMulti = !empty(array_filter($array, function($e) {
return is_array($e);
}));
This function will return int number of array dimensions (stolen from here).
function countdim($array)
{
if (is_array(reset($array)))
$return = countdim(reset($array)) + 1;
else
$return = 1;
return $return;
}
Try as follows
if (count($arrayList) != count($arrayList, COUNT_RECURSIVE))
{
echo 'arrayList is multidimensional';
}else{
echo 'arrayList is no multidimensional';
}
$is_multi_array = array_reduce(array_keys($arr), function ($carry, $key) use ($arr) { return $carry && is_array($arr[$key]); }, true);
Here is a nice one liner. It iterates over every key to check if the value at that key is an array. This will ensure true

Categories