How to extract only Numbers from an Array?
$myarray = array("A","B", "2","D");
I want to get numeric values ("2" in this example) from an array to a variable
You can use is-numeric and array-filter (PHP build-in functions):
$myarray = array("A", "B", "2", "D", "3");
$b = array_filter($myarray, "is_numeric");
Now $b is an array containing the strings: 2 and 3.
Edited Regarding your comment: if you have only 1 value and you want to add 10 to it you can do:
$myarray = array("A", "B", "2", "D");
$b = array_filter($myarray, "is_numeric");
$c = array_values($b); //reset the keys
$finalvalue = $c[0] + 10; // will output 12
<?php
$input = array('A','B', '2.2','D');
foreach($input as $v)
is_numeric($v) && $nums[] = $v;
// Take the first numeric found and add 10.
$result = isset($nums[0]) ? $nums[0] + 10 : null;
var_dump($result);
Output:
float(12.2)
Related
I have arrays like these :
$array1 = [1,2,3];
$array2 = [3,2,1];
$array3 = [2,1,3];
$array4 = [2,1,3];
$array5 = [1,1,1];
$array6 = [3,3,2];
$array7 = [1,2,1];
$array8 = [8,9,2];
I want to check how array2 until array8 compare to array1. It should give me expected return like this :
$array2 = [3,2,1]; return 'match'
$array3 = [2,1,3]; return 'match'
$array4 = [2,3,1]; return 'match'
$array5 = [1,1,1]; return 'not match'
$array6 = [3,3,2]; return 'not match'
$array7 = [1,2,1]; return 'not match'
$array8 = [8,9,2]; return 'not match'
I tried to compare it using array_diff() but sometimes the result is not like what I expected, especially if on array2 have two same values.
note : array2 until array8 need to always have all 3 values from array1
You just need to sort both arrays before comparing them e.g.
sort($array1);
for ($i = 2; $i <= 8; $i++) {
sort(${"array$i"});
echo "array $i: " . ($array1 == ${"array$i"} ? 'match' : 'no match') . "\n";
}
Output:
array 2: match
array 3: match
array 4: match
array 5: no match
array 6: no match
array 7: no match
array 8: no match
Demo on 3v4l.org
You can use array_unique() and then array_diff() for this task:
$array1 = array_unique($array1);
$array2 = array_unique($array2);
$result = array_diff($array1, $array2);
Description of array_unique():
array_unique ( array $array [, int $sort_flags = SORT_STRING ] ) : array
array_unique — Removes duplicate values from an array
Sorting type flags:
SORT_REGULAR - compare items normally (don't change types)
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - compare items as strings, based on the current locale.
You need to sort the arrays so that indexing will be comparable.
Take a parent array and add all array elements in it.
Loop over the parent array.
sort() children arrays.
Compare there and you will get results.
Code:
<?php
$array1 = [1,2,3];
$array2 = [3,2,1];
$array3 = [2,1,3];
$array4 = [2,1,3];
$array5 = [1,1,1];
$array6 = [3,3,2];
$array7 = [1,2,1];
$array8 = [8,9,2];
$arr['array_1'] = [1,2,3];
$arr['array_2'] = [3,2,1];
$arr['array_3'] = [2,1,3];
$arr['array_4'] = [2,1,3];
$arr['array_5'] = [1,1,1];
$arr['array_6'] = [3,3,2];
$arr['array_7'] = [1,2,1];
$arr['array_8'] = [8,9,2];
$find = [1,2,3];
if (! empty($arr)) {
foreach ($arr as $key => $elem) {
sort($arr[$key]);
if ($arr[$key] == $find) {
echo "<br/>[" . implode(',', $elem) . "]: Match";
}
else {
echo "<br/>[" . implode(',', $elem) . "]: No Match";
}
}
}
Output:
[1,2,3]: Match
[3,2,1]: Match
[2,1,3]: Match
[2,1,3]: Match
[1,1,1]: No Match
[3,3,2]: No Match
[1,2,1]: No Match
[8,9,2]: No Match
Although using array_diff is okay, there's an easier way to compare two arrays you can just use ==
<?php
$array1 = [1,2,3];
$array2 = [3,2,1];
$array3 = [2,1,3];
$array4 = [2,1,3];
$array5 = [1,1,1];
$array6 = [3,3,2];
$array7 = [1,2,1];
$array8 = [8,9,2];
for($i = 2; $i <= 8; ++$i) {
sort(${"array$i"});
echo ${"array$i"} == $array1 ? 'match' : 'not match';
echo PHP_EOL;
}
output:
match
match
match
not match
not match
not match
not match
PHP MANUAL
$a == $b Equality TRUE if $a and $b have the same key/value pairs.
$a === $b Identity TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
The fastest way would be to convert your array to associative one. You can use array_flip function to achieve it. Then you need only to check difference in keys which should be fast using array_diff_key. For example:
$array1 = [1,2,3];
$array2 = [3,2,1];
$array3 = [2,1,3];
$array4 = [2,1,3];
$array5 = [1,1,1];
$array6 = [3,3,2];
$array7 = [1,2,1];
$array8 = [8,9,2];
var_dump(
empty( // if it's empty then the arrays are identical
array_diff_key(array_flip($array1), array_flip($array5))
)
);
But this will only work if you don't care if any array contains duplicate values. If number or order of elements is important then this won't work.
at first need to reduce duplicate data from each array by using php array_unique function
Then make difference two array by using array_diff function
<?php
$firstArray = array_unique($firstArray);
$secondArray = array_unique($secondArray);
$arrayDiff = array_diff($firstArray, $secondArray);
?>
This is the source of what i am trying to do:
source: a11993b18486c13240388
What i vae done so far:
$array = preg_split("/(,?\s+)|((?<=[a-z])(?=\d))|((?<=\d)(?=[a-z]))/i", $ref);
I am trying to convert the resulting $array into an object:
[
"a",
"11993",
"b",
"18486",
"c",
"13240388"
]
by grouping by 2 where first item is key and second is value:
Following is my desired outcome:
{
"a"=>"11993",
"b"=>"18486",
"c"=>"13240388"
}
Maybe there is even a better way to do that?
I would appreciate if someone kindly guide me about that.
You need to loop through array using for and in loop add values to new array.
$newArr = [];
for ($i=0; $i<count($arr); $i+=2)
$newArr[$arr[$i]] = $arr[$i+1];
Result
Array
(
[a] => 11993
[b] => 18486
[c] => 13240388
)
Check result in demo
Also if you want to do this using regex on string use
$ref = "a11993b18486c13240388";
preg_match_all("/([a-z])(\d+)/i", $ref, $matches);
$newArr = array_combine($matches[1], $matches[2]);
Check result in demo
try following :
$list = array(
"a",
"11993",
"b",
"18486",
"c",
"13240388"
);
$new_list = array();
for($i=0;$i<count($list);$i=$i+2) {
$new_list[$list[$i]] = $list[$i+1];
}
echo '<pre>'; print_r($new_list); echo '</pre>';
i hope answer to your question is this, because you are looking for object:-
$arr=[
"a",
"11993",
"b",
"18486",
"c",
"13240388"
];
$arrForObj = [];
for ($i=0; $i<count($arr); $i+=2){
$arrForObj[$arr[$i]] = $arr[$i+1];
}
$obj=(object)$arrForObj;
echo "<pre>";
var_dump($obj);
I have two arrays
$array1 = ["name1","name2","name3","name4"];
$array2 = ["name2","name1","name3","name4"];
What I would like to know is the position changes between the arrays. In the above example the output will be:
$returnArray = [
"name2"=>"up",
"name1"=>"down",
"name3"=>"same",
"name4"=>"same"
];
up = moved position up
down = moved position down
same = stayed on the same position
What is the quickest way to determine the position changes comparing the two arrays?
This should work for you:
Just loop through all unique values of $array1 and check with array_search()
if the value is at the same position, down or up.
<?php
$array1 = ["name1","name2","name3","name4"];
$array2 = ["name2","name1","name3","name4"];
$result = [];
foreach(array_unique($array1) as $k => $v){
$result[$v] = $k == array_search($v, $array2) ? "same" : ($k < array_search($v, $array2) ? "up": "down");
}
print_r($result);
?>
And in PHP 7 just use the spaceship operator, e.g.
<?php
$array1 = ["name1","name2","name3","name4"];
$array2 = ["name2","name1","name3","name4"];
$arr = ["-1" => "down", "0" => "same", "1" => "up"];
$result = [];
foreach(array_unique($array1) as $k => $v){
$result[$v] = $arr[array_search($v, $array2) <=> $k];
}
print_r($result);
?>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I have 19 variables in a php file.
$a = 20;
$b = 23;
$c = 2;
$d = 92;
$e = 51;
$f = 27;
$g = 20;
$h = 20;
.....
.....
$s = 32;
What i need, I need to show only top 5 value. And there is similar value for some variables. In that case, I need to show the first value only if it is in the top 5 value.
I am not having any clue on doing this.
After receiving some feedback given bellow, i have used array and asort
Here is the example-
<?php
$fruits = array("a" => "32", "b" => "12", "c" => "19", "d" => "18");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
The output looks like this:
b = 12 d = 18 c = 19 a = 32
I need the reverse result. Meaning, 32, 19, 18, 12.....
Any help. Just dont know the exact command
This is best done by putting the values of the variables into an array and running
sort($arr); (this is from lowes to highest).
rsort($arr); sorts high to low.
http://php.net/manual/en/array.sorting.php
Then you can get the first values at array-index 0,1,2,3 and 4 which will be the biggest numbers.
So:
$arr= array ($a,$b,$c, ....);
rsort($arr);
var_dump($arr); // gives the output.
$arr[0] // biggest number
$arr[4] // 5th biggest number.
A funny way to do this:
$a = 20;
$b = 23;
$c = 2;
$d = 92;
$e = 51;
$f = 27;
$g = 20;
$h = 20;
$array = compact(range('a', 'h'));
rsort($array);
foreach(array_slice($array, 0, 5) as $top) {
echo $top, "\n";
}
Output
92
51
27
23
20
Demo: http://3v4l.org/Wi8q7
Do they need to be individual variables? Storing the values in an array is a better option. So, either manually put all the variables into an array, or change your structure to something more like:
$arr = array(
'a' = 20,
'b' = 23,
'c' = 2,
'd' = 92,
'e' = 51,
....
....
's' => 32
);
or similar. Then use sort() to sort the array:
sort($arr);
To get the top 5, use array_slice():
$arr = array_slice($arr, 0, 5);
See demo
Note: sort() may not be best option for you depending on the desired result. For other sorting options, consult the manual: http://php.net/manual/en/array.sorting.php
<?php
array_push($data,$a);
array_push($data,$b);
.
.
.
$sorted_array = usort($data, 'mysort');
$top5 = array_splice($sorted_array,5);
if(in_array($your_variable,$top5)){
return $top5[0];
}else {
return $top5;
}
function mysort($a,$b){
if ($a == $b) {
return 0;
}
return ($a < $b) ? 1 : -1;
}
?>
$array=array();
for ($i=97;$i<=115;$i++){ //decimal char codes for a-s
$var =chr($i);
$array[]= $$var; //variable variable $a- $s
}
asort($array);
var_dump($array);
Is there a quick way in php to check if 2 arrays contain the same items while the order can be different.
This works for integer arrays How to check if two indexed arrays have same values even if the order is not same in PHP?
//these must be considered equal
array(1,2,3);
array(2,1,3);
array(3,1,2);
//However it must also be possible for strings
array("foo", "bar");
array("bar", "foo");
use this
$is_equal = (count($arr1)==count($arr2)) && !count(array_diff($arr1, $arr2));
use this
Sort both the array
sort($arr1);
sort($arr2);
Compare both by converting them to string - any of the following way.
echo (implode(" ", $arr1) == implode(" ",$arr2))? "true":"false";
/* or */
echo (print_r($arr1,true) == print_r($arr2,true))? "true":"false";
I found a pretty nice solution myself.
$ar1 = array("hello","world","foo");//equals
$ar2 = array("world","foo","hello");//equals
$ar3 = array("hello","world","bar");//not equal
$ar4 = array();
//Add all items to a single array
$ar4 = array_merge($ar1, $ar2);//equal
//OR
$ar4 = array_merge($ar1, $ar3);//not equal
//Remove all duplicates
//$ar4 = array_unique($ar4); edited due to comment below
$ar4 = array_flip($ar4);
//if you want to user $ar4 later flip it again, its still faster than unique
$ar4 = array_flip($ar4);
$c1 = count($ar1);// = 3
$c4 = count($ar4);// = 3 when the arrays were equal and is > 3 if not
if($c1 === $c4){ //CODE }
So for short this is
$ar1 = array("hello","world","foo");
$ar2 = array("world","foo","hello");
$ar4 = array_merge($ar1, $ar2);
//$ar4 = array_unique($ar4); edited due to comment below
$ar4 = array_flip($ar4);
if(count($ar1) === count($ar4)){ //code }
You can sort arrays and then compare them:
function arrays_are_equal($arr1, $arr2) {
sort($arr1);
sort($arr2);
return $arr1 == $arr2;
}
$arr1 = [1, 2, 3, 4];
$arr2 = [2, 3, 1, 4];
arrays_are_equal($arr1, $arr2); // true