get values on same index in PHP - php

I have 2D array and want to get all values which are at same index say at index '1'. what is the best way to get that as a new array.
Example: we have array(array(1,2,3), array(5,6,7)), the result must be array(2, 6).
Thanks

A simple function would do the trick:
function foobar($array, $index) {
$result = array();
foreach($array as $subarray) {
if(isset($subarray[$index])) {
$result[] = $subarray[$index];
}
}
return $result;
}
Or you can just use array_map (requires PHP 5.3):
array_map(function($array) { return $array[1]; }, $input);

$sample = array(array(1,2,3),
array(4,5,6),
array(7,8,9)
);
$index = 1;
$result = array_map(function($value) use($index) { return $value[$index]; }, $sample);
var_dump($result);

$input = array(
array(1,2,3),
array(5,6,7)
);
$output = array();
foreach ( $input as $data ) {
$output[] = $data[1];
}

$myarray=array(array(1,2,3), array(5,6,7));
$index=1;
$result=array();
foreach($myarray as $a) $result[]=$a[$index];
print_r($result);

Related

PHP - UNSET values in array not containing prefix [duplicate]

This question already has answers here:
Native function to filter array by prefix
(6 answers)
Closed 3 months ago.
I have an array like:
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
I want to UNSET the values in the array that are not prefixed with OPTM.
How should that be done?
PHP 5.5
A short approach to reach the same value
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
$filtred = array_filter($array, function($item){
return (strncmp($item, 'OPTM', 4)==0);
});
var_dump($filtred);
to make your code more dynamic and optimal you can do like this
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
$prefix = 'OPTM';
$array = array_filter($array, function($item) use($prefix){
return (strncmp($item, $prefix, strlen($prefix))==0);
});
var_dump($array);
// Don't need this if using PHP 8
if (!function_exists('str_starts_with')) {
function str_starts_with($haystack, $needle) {
return (string)$needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
}
}
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
for ($i = 0; $i < count($array); ++$i) {
if (!str_starts_with($array[$i], 'OPTM'))
unset($array[$i]);
}
// Optional to re-index array
$array = array_values($array);
You can use foreach/str_contains/unset like:
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
foreach($array as $key => $value){
if(!str_contains($value,'OPTM')){
unset($array[$key]);
}
}
print_r($array);
/*
Array
(
[0] => OPTM3000
[2] => OPTM3002
[5] => OPTM3004
)
*/
Reference:
foreach
str_contains
unset
Use this
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
$new_array = array_filter($array, function($v,$k) {
return strpos($v,'OPTM') !==false;
}, ARRAY_FILTER_USE_BOTH);
try this
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
$newArray = array();
foreach($array as $value) {
if ( 'OPTM' == substr($value, 0, 4) ) {
$newArray[] = $value;
}
}
Use Unset or if you don like to use unset function one possible way will be to work with array_map and array_filter:
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
$arr = array_map(function($item) {
if ( str_contains($item,'OPTM')) {
return $item;
}
}, $array);
$arr = array_filter($arr);
print_r($arr);
You can iterate the elements in your array using a regex like:
foreach($array as $element){
$pattern = "OPTM/";
if(echo preg_match($pattern, $element) == 0){
$key = array_search($element, $array);
unset($array[$key]);
}
}
OK, this works for me.
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
$allowed_prefix = 'OPTM';
foreach ( $array as $key => $text )
{
if (strpos($text, $allowed_prefix) !== 0) {
unset($array[$key]);
}
}

How to combine an array with the same index

I have an array as follows
[{"2":[2]},{"9":[4,10,11,12,13,14,15,16,17,19,20,21,22,23,24,25,26,27,28,30,32,33,34,36,41]},{"2":[5,6,9]},{"7":[7,8]},{"9":[3]}]
is there any possible way to combine the value for the same index ?
Yes, it is possible decoding the json string and using array_reduce:
$arr = json_decode('[{"2":[2]},{"9":[4,10,11,12,13,14,15,16,17,19,20,21,22,23,24,25,26,27,28,30,32,33,34,36,41]},{"2":[5,6,9]},{"7":[7,8]},{"9":[3]}]');
$arr = array_reduce($arr, function ($carry, $item) {
$key = key($item);
if (isset($carry[$key])) {
$carry[$key]->$key = array_merge($carry[$key]->$key, $item->$key);
} else {
$carry[$key] = $item;
}
return $carry;
});
echo json_encode(array_values($arr));
The result is:
[{"2":[2,5,6,9]},{"9":[4,10,11,12,13,14,15,16,17,19,20,21,22,23,24,25,26,27,28,30,32,33,34,36,41,3]},{"7":[7,8]}]
<?php
$json = '[{"2":[2]},{"9":[4,10,11,12,13,14,15,16,17,19,20,21,22,23,24,25,26,27,28,30,32,33,34,36,41]},{"2":[5,6,9]},{"7":[7,8]},{"9":[3]}]';
$multi_array = json_decode($json, true);
$result = [];
foreach($multi_array as $arr)
{
foreach($arr as $k => $v)
{
$temp = isset($result[$k]) ? $result[$k] : [];
$result[$k] = array_merge($temp, $v);
}
}
print_r($result);
This is another option:
$old = json_decode('[{"2":[2]},{"9":[4,10,11,12,13,14,15,16,17,19,20,21,22,23,24,25,26,27,28,30,32,33,34,36,41]},{"2":[5,6,9]},{"7":[7,8]},{"9":[3]}]', true);
$new = [];
array_map(function ($arr) use (&$new) {
$key = key($arr);
$new[$key] = array_merge(current($arr), !empty($new[$key]) ? $new[$key] : []);
}, $old);
echo json_encode($new);
Output:
{"2":[5,6,9,2],"9":[3,4,10,11,12,13,14,15,16,17,19,20,21,22,23,24,25,26,27,28,30,32,33,34,36,41],"7":[7,8]}

How to divide an array to two dimensional array in PHP

I have an array like below.
$arr=array('0_1','0_3','1_2',1_1','4_1');
can i divide it into
$arr[0][1]='0_1';
$arr[0][3]='0_3';
...
Thanks.
$newArray = [];
foreach ($arr as $item) {
$items = explode('_', $item);
$newArray[$items[0]][$items[1]] = $item;
}
var_dump($newArray);
exit();
This should do the trick. You should have a look at the explode function
Another way to do this without foreach loop. :->
$arr = array('0_1','0_3','1_2','1_1','4_1');
$result = [];
array_walk($arr,function($v,$k)use (&$result){
$data = explode("_",$v);
$result[$data[0]][$data[1]] = $v;
});
print_r($result);
$arrv = array('0_1','0_3','1_2','1_1','4_1');
$newArray = [];
array_walk($arrv,function($value,$key){
global $newArray;
$indexArray = explode("_",$value);
$newArray[$indexArray[0]][$indexArray[1]] = $value;
});
var_dump($newArray);

How do i get unique value from an array?

$a=array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
From the above array i need the value Dog alone. how can i get the unique value from an array?. is there any functions in php?...
Thanks
Ravi
Have a look at:
http://php.net/function.array-unique
and maybe:
http://php.net/function.array-count-values
$a = array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
$counted = array_count_values($a);
$result = array();
foreach($counted as $key => $value) {
if($value === 1) {
$result[] = $key;
}
}
//$result is now an array of only the unique values of $a
print_r($result);
function getArrayItemByValue($search, $array) {
// without any validation and cheking, plain and simple
foreach($array as $key => $value) {
if($search === $value) {
return $key;
}
}
return false;
}
then try using it:
echo $a[getArrayitembyValue('Dog', $a)];
Try with:
$a = array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
$aFlip = array_flip($a);
$unique = array();
foreach ( array_count_values( $a ) as $key => $count ) {
if ( $count > 1 ) continue;
// $unique[ array_search($key) ] = $key;
$unique[ $aFlip[$key] ] = $key;
}
Use following function seems to be working & handy.
<?php
$array1 = array('foo', 'bar', 'xyzzy', 'xyzzy', 'xyzzy');
$dup = array_unique(array_diff_assoc($array1, array_unique($array1)));
$result = array_diff($array1, $dup);
print_r($result);
?>
You can see its working here - http://codepad.org/Uu21y6jf
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
$result = array_unique(a);
print_r($result);
try this one...

How to get values in an array this way with PHP?

From:
$arr = array(array('key1'=>'A',...),array('key1'=>'B',...));
to:
array('A','B',..);
$output = array();
foreach ($arr as $array_piece) {
$output = array_merge($output, $array_piece);
}
return array_values($output);
On the other hand, if you want the first value from each array, what you want is...
$output = array();
foreach ($arr as $array_piece) {
$output[] = array_unshift($array_piece);
}
But I'm thinking you want the first one.
Relatively simple conversion by looping:
$newArray = array()
foreach ($arr as $a) {
foreach ($a as $key => $value) {
$newArray[] = $value;
}
}
Or, perhaps more elegantly:
function flatten($concatenation, $subArray) {
return array_merge($concatenation, array_values($subArray));
}
$newArray = array_reduce($arr, "flatten", array());
John's solution is also nice.
Something like this should work
<?
$arr = array(array('key1'=>'A','key2'=>'B'),array('key1'=>'C','key2'=>'D'));
$new_array = array();
foreach ($arr as $key => $value) {
$new_array = array_merge($new_array, array_values($value));
}
var_export($new_array);
?>
If you want all the values in each array inside your main array.
function collapse($input) {
$buf = array();
if(is_array($input)) {
foreach($input as $i) $buf = array_merge($buf, collapse($i));
}
else $buf[] = $input;
return $buf;
}
Above is a modified unsplat function, which could also be used:
function unsplat($input, $delim="\t") {
$buf = array();
if(is_array($input)) {
foreach($input as $i) $buf[] = unsplat($i, $delim);
}
else $buf[] = $input;
return implode($delim, $buf);
}
$newarray = explode("\0", unsplat($oldarray, "\0"));

Categories