PHP array check all values is equal - php

array
0 =>
array
'point' => string '2'
1 =>
array
'point' => string '4'
2 =>
array
'point' => string '1'
I need checking values of 'point' in above array, if all values of 'point' is '4' it will return true as below array.
array
0 =>
array
'point' => string '4'
1 =>
array
'point' => string '4'
2 =>
array
'point' => string '4'

You just need to use 2 statements fomr PHP. if and for.
I used following script to test it (you can choose one of the loops(for or foreach))
$test = array(array('point' => 4), array('point' => 4));
function checkArrayForPointValue($array, $expectedValue)
{
$ok = true;
for ($i = 0; $i < count($array); $i++) {
if ($array[$i]['point'] != $expectedValue) {
$ok = false;
break;
}
}
// choose one of them
foreach ($array as $element) {
if ($element['point'] != $expectedValue) {
$ok = false;
break;
}
}
return $ok;
}
print(checkArrayForPointValue($test, '4') ? 'yay' : 'not yay');

Compare each value in a foreach :
function arrayComparePoint($array) {
$valueCompare = $array[0]['point'];
foreach ($array as $arrayPoint) {
foreach ($arrayPoint as $point) {
if ($valueCompare != $point) {
return false;
}
}
}
return true;
}

Simply use as
function checkArray($myArray) {
$result = array_unique(array_column($myArray, 'point'));
return (count($result) == 1 && $result[0] == '4') ? "true" : "false";
}
echo checkArray($myArray);

Related

How to get array values certain condition

There is something I want to ask to take the array value based on the biggest score in score keys and the smallest strlen in word keys, this sample array:
<?php
$data = array(
'0' => array('score' => '4','word' => 'titiek'),
'1' => array('score' => '4','word' => 'titik'),
'2' => array('score' => '4','word' => 'titie'),
'3' => array('score' => '3','word' => 'tuatuka'),
'4' => array('score' => '3','word' => 'titiks'),
);
$result = //do something??
print_r($result);
?>
let we see in $data array, condition the biggest score and the smallest strlen we have $data[1] and $data[2], right? but, I need the first queue. the result print_r($result) is a:
Array ( [score] => 4 [word] => titik )
You can use usort to sort your array by score and then word length, and then your desired result will be in $data[0]. Note that we rank equal word lengths higher so that we return the first one of the shortest length that we see in the array.
usort($data, function($a, $b) {
if ($a['score'] == $b['score'])
return (strlen($a['word']) >= strlen($b['word'])) ? 1 : -1;
else
return $b['score'] - $a['score'];
});
print_r($data[0]);
An alternate method (not relying on usort behaviour) is to find the maximum score and then process the array looking for the first, shortest string with that score:
$max_score = max(array_column($data, 'score'));
$minlength = PHP_INT_MAX;
foreach ($data as $key => $value) {
if ($value['score'] != $max_score) continue;
if (strlen($value['word']) < $minlength) {
$minlength = strlen($value['word']);
$index = $key;
}
}
print_r($data[$index]);
Output (same for both):
Array (
[score] => 4
[word] => titik
)
Demo on 3v4l.org
You can use array_reduce and by using ">=" "<=" it will keep the previous value
$result = array_reduce($data, function ($previous, $current) {
return $previous['score'] >= $current['score'] && strlen($previous['word']) <= strlen($current['word']) ? $previous : $current;
});
var_dump($result);
Here is how you can find it:
$data = array(
'0' => array('score' => '4','word' => 'titiek'),
'1' => array('score' => '4','word' => 'titik'),
'2' => array('score' => '4','word' => 'titie'),
'3' => array('score' => '3','word' => 'tuatuka'),
'4' => array('score' => '3','word' => 'titiks'),
);
$maxScore = 0; $minLen = 0;
foreach($data as $key => $arr) {
$score = $arr['score'];
$len = strlen($arr['word']);
if($score > $maxScore) {
$maxKey = $key;
$minLen = $len;
$maxScore = $score;
} else if ($score == $maxScore && $len < $minLen) {
$maxKey = $key;
$minLen = $len;
}
}
var_dump($data[$maxKey]);
I have used var_dump to show the result. $data[$maxKey] is the required result.

Custom Array Sorting by input string and position

I have an array. It' looks like:
$arr = [
'0' => ['id'=>9, 'q'=>'motor', 'pos'=>1],
'1' => ['id'=>10, 'q'=>'NULL', 'pos'=>0],
'2' => ['id'=>7, 'q'=>'motor', 'pos'=>2],
'3' => ['id'=>8, 'q'=>'NULL', 'pos'=>0],
'4' => ['id'=>11, 'q'=>'motor','pos'=>3],
'5' => ['id'=>11, 'q'=>'exhaust','pos'=>1]
];
How can I sort the data above to make it looks like (if q='motor' is inside search string):
$arr = [
'0' => ['id'=>9, 'q'=>'motor', 'pos'=>1],
'2' => ['id'=>7, 'q'=>'motor', 'pos'=>2],
'4' => ['id'=>11, 'q'=>'motor','pos'=>3],
'1' => ['id'=>10, 'q'=>'NULL', 'pos'=>0],
'3' => ['id'=>8, 'q'=>'NULL', 'pos'=>0],
'5' => ['id'=>11, 'q'=>'exhaust','pos'=>1]
];
So:
function custom_sort($input_query, $arr) {
foreach($arr as $key=>$row) {
if (strpos($input_query, $row['q'])) {
... How to Sort By Pos?
}
}
}
Thanks!
Updated (question/answer)
p.s: I'm trying to use custom variable as input: $q
usort($arr, function($a, $b) use ($q) {
if ($a['q'] == $q) {
if($b['q'] == $q) {
return ($a['pos'] > $b['pos']) ? 1 : -1;
}
return -1;
}
if ($b['q'] == $q) {
return 1;
}
return 0;
});
And the function stop working. How can I solve this?
Here's a usort that handles your requirements, wrapped in a function that transforms the array in place:
Items with q key containing $query will be placed at the front of the array.
Items with q key containing $query will be sorted ascending by their pos value.
Everything else will be sorted by its pos value.
function custom_sort($query, &$arr) {
usort($arr, function($a, $b) use ($query) {
$in_a = strpos($a['q'], $query) !== false;
$in_b = strpos($b['q'], $query) !== false;
if ($in_a && !$in_b) {
return -1;
}
if (!$in_a && $in_b) {
return 1;
}
return $a['pos'] - $b['pos'];
});
}
custom_sort("motor", $arr);
You can use usort
usort($arr, function($a, $b) {
if ($a['q'] == 'motor') {
if($b['q'] == 'motor') {
return ($a['pos'] > $b['pos']) ? 1 : -1;
}
return -1;
}
if ($b['q'] == 'motor') {
return 1;
}
return 0;
});
If you need a different order, just change the function to match your needs.
U sort would help you here
usort( $arr, function ( $a, $b ) {
if ( $a['q'] === $b['q'] ) {
return $a['pos'] < $b['pos'] ? -1 : 1;
}
if ( $a['q'] === 'motor' ) {
return -1;
}
if ( $b['q'] === 'motor' ) {
return 1;
}
return 0;
} );

Get corresponding array values from same index [duplicate]

using array_search in a 1 dimensional array is simple
$array = array("apple", "banana", "cherry");
$searchValue = "cherry";
$key = array_search($searchValue, $array);
echo $key;
but how about an multi dimensional array?
#RaceRecord
[CarID] [ColorID] [Position]
[0] 1 1 3
[1] 2 1 1
[2] 3 2 4
[3] 4 2 2
[4] 5 3 5
for example i want to get the index of the car whose position is 1. How do i do this?
In php 5.5.5 & later versions,
you can try this
$array_subjected_to_search =array(
array(
'name' => 'flash',
'type' => 'hero'
),
array(
'name' => 'zoom',
'type' => 'villian'
),
array(
'name' => 'snart',
'type' => 'antihero'
)
);
$key = array_search('snart', array_column($array_subjected_to_search, 'name'));
var_dump($array_subjected_to_search[$key]);
Output:
array(2) { ["name"]=> string(5) "snart" ["type"]=> string(8) "antihero" }
working sample : http://sandbox.onlinephpfunctions.com/code/19385da11fe0614ef5f84f58b6dae80bd216fc01
Documentation about array_column can be found here
function find_car_with_position($cars, $position) {
foreach($cars as $index => $car) {
if($car['Position'] == $position) return $index;
}
return FALSE;
}
You can try this
array_search(1, array_column($cars, 'position'));
Hooray for one-liners!
$index = array_keys(array_filter($array, function($item){ return $item['property'] === 'whatever';}))[0];
Let's make it more clear:
array_filter(
$array,
function ($item) {
return $item['property'] === 'whatever';
}
);
returns an array that contains all the elements that fulfill the condition in the callback, while maintaining their original array keys. We basically need the key of the first element of that array.
To do this we wrap the result in an array_keys() call and get it's first element.
This specific example makes the assumption that at least one matching element exists, so you might need an extra check just to be safe.
I basically 'recreated' underscore.js's findWhere method which is to die for.
The function:
function findWhere($array, $matching) {
foreach ($array as $item) {
$is_match = true;
foreach ($matching as $key => $value) {
if (is_object($item)) {
if (! isset($item->$key)) {
$is_match = false;
break;
}
} else {
if (! isset($item[$key])) {
$is_match = false;
break;
}
}
if (is_object($item)) {
if ($item->$key != $value) {
$is_match = false;
break;
}
} else {
if ($item[$key] != $value) {
$is_match = false;
break;
}
}
}
if ($is_match) {
return $item;
}
}
return false;
}
Example:
$cars = array(
array('id' => 1, 'name' => 'Toyota'),
array('id' => 2, 'name' => 'Ford')
);
$car = findWhere($cars, array('id' => 1));
or
$car = findWhere($cars, array(
'id' => 1,
'name' => 'Toyota'
));
I'm sure this method could easily reduce LOC. I'm a bit tired. :P
actually all array functions are designed for single dimension array.You always need to keep in mind that you are applying it on single dimension array.
function find_car_with_position($cars, $position) {
for($i=0;$i<count($cars);$i++){
if(array_search($search_val, $cars[$i]) === false){
// if value not found in array.....
}
else{
// if value is found in array....
}
}
}

Php Array key=> value searching

HI I am fairly new to php.
I have an array
$arr = array(0 => array('GID'=>1,'groupname'=>"cat1",'members'=>array(0=>array('mid'=>11,'mname'=>'wwww'),1=>array('mid'=>12,'mname'=>'wswww'))),
1 => array('GID'=>2,'groupname'=>"cat2",'members'=>array(0=>array('mid'=>13,'mname'=>'gggwwww'),1=>array('mid'=>14,'mname'=>'wvvwww'))),
2 => array('GID'=>3,'groupname'=>"cat1",'members'=>array(0=>array('mid'=>15,'mname'=>'wwddsww')),1=>array('mid'=>16,'mname'=>'wwwdddw')));
ie...,I have GID,groupname,mid(member id),mname(member name).I want to insert a new mid and mname into a group if it is already in the array ,if it is not exists then create a new subarray with these elements..I also need to check a member id(mid) is also present.........................I used the code but its not working fine............. if (!empty($evntGroup)) {
foreach ($evntGroup as $k => $group) {
if ($group['GID'] == $group_id) {
foreach($group as $j=> $mem){
if($mem['mid'] == $mem_id){
unset($evntGroup[$k]['members'][$j]['mid']);
unset($evntGroup[$k]['members'][$j]['mname']);
}
else{
$evntGroup[$k]['members'][] = array(
'mid' => $mem_id,
'mname' => $mem_name);
}}
} else {
$evntGroup[] = array(
'GID' => $group_id,
'groupname' => $Group['event_group_name'],
'members' => array(
0 => array(
'mid' => $mem_id,
'mname' => $mem_name
)
)
);
}
}
} else {
$evntGroup[$i]['GID'] = $group_id;
$evntGroup[$i]['groupname'] = $Group['event_group_name'];
$evntGroup[$i]['members'][] = array(
'mid' => $mem_id,
'mname' => $mem_name);
$i++;
}
In the form of a function, the easiest solution will look something like this:
function isGidInArray($arr, $val) {
foreach($arr as $cur) {
if($cur['GID'] == $val)
return true;
}
return false;
}
You've updated your question to specify what you want to do if the specified GID is found, but that's just a trivial addition to the loop:
function doSomethingIfGidInArray($arr, $val) {
foreach($arr as $cur) {
if($cur['GID'] == $val) {
doSomething();
break; //Assuming you only expect one instance of the passed value - stop searching after it's found
}
}
}
There is unfortunately no native PHP array function that will retrieve the same index of every array within a parent array. I've often wanted such a thing.
Something like this will match if GID equals 3:
foreach( $arr as $item ) {
if( $item['GID'] == 3 ) {
// matches
}
}
There is the code
function updateByGid(&$array,$gid,$groupname,$mid,$mname) {
//For each element of the array
foreach ($array as $ii => $elem) {
//If GID has the same value
if ($elem['GID'] == $gid) {
//Insert new member
$array[$ii]['members'][]=array(
'mid'=>$mid,
'mname'=>$mname);
//Found!
return 0;
}
}
//If not found, create new
$array[]=array(
'GID'=>$gid,
'groupname'=>$groupname,
'members'=>array(
0=>array(
'mid'=>$mid,
'mname'=>$mname
)
)
);
return 0;
}

php, long and deep matrix

I have a deep and long array (matrix). I only know the product ID.
How found way to product?
Sample an array of (but as I said, it can be very long and deep):
Array(
[apple] => Array(
[new] => Array(
[0] => Array([id] => 1)
[1] => Array([id] => 2))
[old] => Array(
[0] => Array([id] => 3)
[1] => Array([id] => 4))
)
)
I have id: 3, and i wish get this:
apple, old, 0
Thanks
You can use this baby:
function getById($id,$array,&$keys){
foreach($array as $key => $value){
if(is_array( $value )){
$result = getById($id,$value,$keys);
if($result == true){
$keys[] = $key;
return true;
}
}
else if($key == 'id' && $value == $id){
$keys[] = $key; // Optional, adds id to the result array
return true;
}
}
return false;
}
// USAGE:
$result_array = array();
getById( 3, $products, $result_array);
// RESULT (= $result_array)
Array
(
[0] => id
[1] => 0
[2] => old
[3] => apple
)
The function itself will return true on success and false on error, the data you want to have will be stored in the 3rd parameter.
You can use array_reverse(), link, to reverse the order and array_pop(), link, to remove the last item ('id')
Recursion is the answer for this type of problem. Though, if we can make certain assumptions about the structure of the array (i.e., 'id' always be a leaf node with no children) there's further optimizations possible:
<?php
$a = array(
'apple'=> array(
'new'=> array(array('id' => 1), array('id' => 2), array('id' => 5)),
'old'=> array(array('id' => 3), array('id' => 4, 'keyname' => 'keyvalue'))
),
);
// When true the complete path has been found.
$complete = false;
function get_path($a, $key, $value, &$path = null) {
global $complete;
// Initialize path array for first call
if (is_null($path)) $path = array();
foreach ($a as $k => $v) {
// Build current path being tested
array_push($path, $k);
// Check for key / value match
if ($k == $key && $v == $value) {
// Complete path found!
$complete= true;
// Remove last path
array_pop($path);
break;
} else if (is_array($v)) {
// **RECURSION** Step down into the next array
get_path($v, $key, $value, $path);
}
// When the complete path is found no need to continue loop iteration
if ($complete) break;
// Teardown current test path
array_pop($path);
}
return $path;
}
var_dump( get_path($a, 'id', 3) );
$complete = false;
var_dump( get_path($a, 'id', 2) );
$complete = false;
var_dump( get_path($a, 'id', 5) );
$complete = false;
var_dump( get_path($a, 'keyname', 'keyvalue') );
I tried this for my programming exercise.
<?php
$data = array(
'apple'=> array(
'new'=> array(array('id' => 1), array('id' => 2), array('id' => 5)),
'old'=> array(array('id' => 3), array('id' => 4))
),
);
####print_r($data);
function deepfind($data,$findfor,$depth = array() ){
foreach( $data as $key => $moredata ){
if( is_scalar($moredata) && $moredata == $findfor ){
return $depth;
} elseif( is_array($moredata) ){
$moredepth = $depth;
$moredepth[] = $key;
$isok = deepfind( $moredata, $findfor, $moredepth );
if( $isok !== false ){
return $isok;
}
}
}
return false;
}
$aaa = deepfind($data,3);
print_r($aaa);
If you create the array once and use it multiple times i would do it another way...
When building the initial array create another one
$id_to_info=array();
$id_to_info[1]=&array['apple']['new'][0];
$id_to_info[2]=&array['apple']['new'][2];

Categories