Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to get the bottom values of an array with a single condition as below :
Get all numeric values until the next value is a string then stop the instruction, and leave all other values even if they are numeric
<? php $data= [1,2,3,'web',4,5,6,'web',7,8,9]; ?>
The output will be : 7,8,9
We can try first filtering to find the first non numeric entry. Then, subset the array starting with this index. Finally, filter the subset again to remove all non numeric elements.
$data= [1,2,3,'web',4,5,6,'web',7,8,9];
$sub_data = array_filter($data, function($item) { return !is_numeric($item); });
$index = array_search(current($sub_data), $data);
$sub_data = array_slice($data, $index);
$sub_data = array_filter($sub_data, function($item) { return is_numeric($item); });
print_r($sub_data);
This prints:
Array
(
[1] => 4
[2] => 5
[3] => 6
[5] => 7
[6] => 8
[7] => 9
)
i don't know if there a specific function for it but i got the same result with this
$data= [1,2,3,'web',4,5,6,'web',7,8,9];
foreach ($data as $key => $value) {
if($value=="web"){
$x =$key;
}
}
$data = array_slice($data,$x);
print_r($data);
Output:
Array ( [0] => web [1] => 7 [2] => 8 [3] => 9 )
You can use array_reverse to get values from the array with elements in reverse order.
$reversed = array_reverse($data);
and then parse the array to stop where it gets a string
foreach($reversed as $value) {
if(is_string($value)) {
break;
}
$output[] = $value;
}
//print_r($output); // to print the output array. This will return the values like 9, 8, 7
// do a reverse again to get the values in the format you want.
$final= array_reverse($output);
print_r($final); // to print the final array. This will return the values like 7, 8, 9
Here is a DEMO
You can just pop values off the end until you get to something that isn't an int.
while (is_int($n = array_pop($data))) {
$result[] = $n;
}
This will modify the data array, so if you need to keep the original values, then do this with a copy.
The test you'll want depends on whether your example data is representative and all the numeric values you want in the array are of type int, or perhaps some might be numeric strings.
$data= [1,2,3,'web',4,5,6,'web',7,8,9];
$result = [];
for($i = count($data)-1; $i >= 0; $i++) {
// If some of the values you want might be numeric strings
// (e.g. "7") or decimals (e.g. 1.5), use this
if(!is_numeric($data[$i])) {
break;
}
// If your values will only be integer type, use this
if(!is_int($data[$i])) {
break;
}
array_unshift($result,$data[$i]);
}
// If you want the results in original order
print_r($result); // Output: [7,8,9]
// If you want the results inverted
$result = array_reverse($result);
print_r($result); // Output: [9,8,7]
Try this, here i am storing values in to an array $newArray if value is integer. if string found in value just reset the array $newArray
<?php
$data = [1,2,3,'web',4,5,6,'web',7,8,9];
$newArray = array(); // resultant array
foreach ($data as $key => $value) {
if(is_int($value)){
$newArray[] = $value;
}
else{
$newArray = array(); // reset if not integer
}
}
echo "<pre>";
print_r($newArray);
?>
DEMO
Result:
Array
(
[0] => 7
[1] => 8
[2] => 9
)
Now, you can use implode() for comma separated result, like:
echo implode(",",$newArray); // 7,8,9
Edit: (08-07-2019)
If Example:
$data = [1,2,3,'web',4,5,6,'web',7,8,9,'web'];
Code:
<?php
$data = [1,2,3,'web',4,5,6,'web',7,8,9,'web'];
$newArray = array(); // resultant array
end($data);
$keyLast = key($data); // fetches the key of the element pointed to by the internal pointer
foreach ($data as $key => $value) {
if(is_int($value) ){
$newArray[] = $value;
}
else{
if($keyLast === $key) { // if last key is string overwrite the previous array.
$newArray = $newArray;
}
else{
$newArray = array(); // reset if not integer
}
}
}
echo "<pre>";
print_r($newArray);
?>
Edit:
It's better to store all integer values into an array and then use array_slice() to get let three elements from new integer array like:
<?php
$data = [1,2,3,'web',4,5,6,'web',7,8,9,'web','web','web'];
$newArray = array(); // resultant array
foreach ($data as $key => $value) {
if(is_int($value) ){
$newArray[] = $value;
}
}
$lastThreeElement = array_values(array_slice($newArray, -3, 3, true));
echo "<pre>";
print_r($lastThreeElement);
?>
Related
Multiple values in a single array (some value similar)
how to get
One of them is to get the array that is similar values
minimum 1 and maximum 2 times repeat
for Example This array -
$array_value = array('ab','ab','cd','de','ab','cd','ab','de','xy');
foreach($array_value as $value){
}
I want output - ab, ab,cd, cd, de, xy
array_count_values return the repetition of specific value in array. So, you can use it to simplify the code and quickly implement it.
$array_value = array('ab','ab','cd','de','ab','cd','ab','de','xy');
// Get count of every value in array
$array_count_values = array_count_values($array_value);
$result_array = array();
foreach ($array_count_values as $key => $value) {
// Get $value as number of repetition of value and $key as value
if($value > 2) {
$value = 2;
array_push($result_array, $key);
array_push($result_array, $key);
} else {
for ($i=0; $i < $value; $i++) {
array_push($result_array, $key);
}
}
}
print_r($result_array);
I think your output shuold have two de not one?
Anyway here is the code with explanations in comments:
<?php
$array_value = array('ab','ab','cd','de','ab','cd','ab','de','xy');
$arr_count = []; //we use this array to keep track of how many times we've added this
$new_arr = []; //we add elements to this array, or not.
foreach($array_value as $value){
// we've added it before
if (isset($arr_count[$value])) {
// we only add it again one more time, no more.
if ($arr_count[$value] < 2) {
$arr_count[$value]++;
$new_arr[] = $value;
}
}
// we haven't added this before
else {
$arr_count[$value] = 1;
$new_arr[] = $value;
}
}
sort($new_arr);
print_r($new_arr);
/*
(
[0] => ab
[1] => ab
[2] => cd
[3] => cd
[4] => de
[5] => de
[6] => xy
) */
PHP Demo
I want to rank the keys of an associative array in php based upon their values. (top to down as 1, 2, 3....). Keys having same value will have same rank.
Here function getRanks() is meant to return an array containing keys and the ranks (number).
I expect it to return like this (this is sorted value wise in descending)
Array
(
[b] => 1
[a] => 2
[d] => 3
[c] => 3
[e] => 4
)
There is issue in assigning the ranks (values) in the $ranks array which is to be returned.
What am I doing wrong? Do these loops even do something?
Code:
$test = array('a'=> 50, 'b'=>60, 'c'=>20, 'd'=>20, 'e'=>10);
$json = json_encode($test);
print_r(getRanks($json));
function getRanks($json) {
$tmp_arr = json_decode($json, TRUE);
$ranks = array();
uasort($tmp_arr, function($a, $b){
return $a == $b ? 0 : $a > $b ? -1 : 1; //descending
});
$keys = array_keys($tmp_arr); //after sorting
$ranks = array_fill_keys($keys, 0); //copy keys
$ranks[$keys[0]] = 1; //first val => rank 1
//------- WORKS FINE UNTIL HERE ------------------
// need to fix the ranks assignment
for($i=1; $i<count($keys)-1; $i++) {
for($j=$i; $j < count($keys)-1; $j++) {
if($tmp_arr[$keys[$j]] == $tmp_arr[$keys[$j+1]]) {
$rank[$keys[$j]] = $i;
}
}
}
return $ranks;
}
Your approach seems unnecessarily complicated. In my version I kept the json-related copying part of it but finished it off in a simpler way:
function getRanks($json) {
$tmp_arr = json_decode($json, TRUE);
asort($tmp_arr);. // sort ascending
$i=0; $lv=null;$ranks = array();
foreach ($tmp_arr as $k=>$v) {
if ($v>$lv){ $i++; $lv=$v;}
$ranks[$k]=$i;
}
return $ranks;
}
See the demo here: https://rextester.com/LTOA23372
In a slightly modified version you you can also do the ranking in a descending order, see here: https://rextester.com/HESQP10053
I've also tried with another approach.
I think it may not be the good solution because of high memory & CPU time consumption.
For small arrays (in my case) it works fine.
(I've posted because it may be an answer)
It creates array of unique values and fetches ranks accordingly.
$test = array('a'=> 50, 'b'=>60, 'c'=>20, 'd'=>20, 'e'=>10);
$json = json_encode($test);
print_r(getRanks($json));
function getRanks($json) {
$tmp_arr = json_decode($json, TRUE);
arsort($tmp_arr);
$uniq_vals = array_values(array_unique($tmp_arr)); // unique values indexed numerically from 0
foreach ($tmp_arr as $k => $v) {
$tmp_arr[$k] = array_search($v, $uniq_vals) + 1; //as rank will start with 1
}
return $tmp_arr;
}
This is the simple thing that you can do it by using php array function check example given below.
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
Here is my array: [["STR_License_Driver",1],["STR_License_Truck",0],["STR_License_Pilot",1],["STR_License_Firearm",0],["STR_License_Rifle",0]]
My goal is to make an array or string (unsure of best method) called results where the value of the licenses is 1.
For example: The results should be something like: STR_Licenses_Driver, STR_Licenses_Pilot.
I am currently using PHP Version 7, and Laravel Version 5.5
JSON Decode the $this->license and do the loop.
Whole code:
$licenses = $this->licenses;//This is your posted array string
$result = json_decode($licenses);
$licenses_with_1 = array();
foreach($result as $i){
foreach($i as $key => $value){
if($value == 1){
$licenses_with_1[] = $i[0];
}
}
}
print_r($licenses_with_1);
Result:
Array ( [0] => STR_License_Driver [1] => STR_License_Pilot )
I remember Python on your data structure.
Try my solution:
https://3v4l.org/nrfqZ
$licenses = [["STR_License_Driver",1],["STR_License_Truck",0],["STR_License_Pilot",1],["STR_License_Firearm",0],["STR_License_Rifle",0]];
Map over filtered array having second item equal to 1 to get the license names.
$filterVal = 1;
$licenseNames = array_map(
function ($item) { return $item[0]; },
array_filter(
$licenses,
function ($item) use ($filterVal) { return $item[1] === $filterVal; }
)
);
Then implode array of license names to join by glue string.
echo implode($licenseNames, ', ');
I've started learning about arrays and they've very confusing. I want to generate 4 numbers using this:
$numbers = range(1,4);
Then I shuffle with this:
shuffle($numbers);
Now I want to get each number as a variable, I've been told the best way is arrays. I have this code:
foreach($numbers as $number){
$test = array("first"=>"$number");
echo $test['first'];
}
What this does is echo all 4 numbers together, like "3142" or "3241" etc. Which is close to what I want, but I need all 4 numbers to have their own variable each. So I made this:
foreach($numbers as $number){
$test = array("first"=>"$number","second"=>"$number","third"=>"$number","fourth"=>"$number");
echo $test['first']," ",$test['second']," ",$test['third']," ",$test['fourth']," <br>";
}
This just echoes the 4 numbers 4 times. I need "first" to be the first number, "second" to be the second number of the 4 and the same for the third and fourth. I've been searching the web but don't know specifically what to search for to find the answer.
If someone answers could they please put as much detail into what certain functions do as possible, I want to learn not just get working code :)
You can use sizeof() it is return size of array size, and pass the key value manually. Like-
echo $numbers[0];
echo $numbers[1];
echo $numbers[2];
Here is a full code, try it
$numbers = range(1,4); //generate four numbers
shuffle($numbers); //shuffle them
$test = array(); //create array for the results
$words = array("1st", "2nd", "3rd", "4th","5th"); //create your array keys
$i=0;
foreach($numbers as $number){
$test[] = array($words[$i]=>$number); //add your array keys & values
$i++;
}
print_r($test); //show your results
If my understanding is correct you have an array and you want certain values from within it?
Then why not just use the array keys:
$array = array('peach','pear','apple','orange','banana');
echo $array[0]; // peach
echo $array[1]; // pear
echo $array[2]; // apple
Or you could loop through the array like so:
foreach ($array as $arrayKey => $arrayValue) {
// First value in the array is now below
echo $arrayKey; // 0
echo $arrayValue; // peach
}
You can also check if a value is in an array like so:
if (in_array('orange', $array)) {
echo 'yes';
}
Edit:
// Our array values
$array = array('peach','pear','apple','orange','banana');
// We won't shuffle for the example, we need expected results
#$array = shuffle($array);
// We want the first 3 values of the array
$keysRequired = array(0,1,2);
// This will hold our results
$storageArray = array();
// So for the first iteration of the loop $arrayKey is going to be 0
foreach ($array as $arrayKey => $arrayValue) {
// If the array key matches one of the values in the required array
if (in_array($arrayKey, $keysRequired)) {
// Store it within the storage array so we know what value it is
$storageArray[] = $arrayValue;
}
}
// Let's see what values have been stored
echo "<pre>";
print_r($storageArray);
echo "</pre>";
Would give you the following:
Array
(
[0] => 'peach'
[1] => 'pear'
[2] => 'apple'
)
Try this:
<?php
$numbers = range(1,4);
shuffle($numbers);
$test = array();
foreach($numbers as $k=>$v){
$test[$k] = $v;
}
echo "<pre>";
print_r($test);
?>
This will give you the output as:
Array
(
[0] => 3
[1] => 4
[2] => 2
[3] => 1
)
After that you can do:
$myvar["first"] = $test[0];
$myvar["second"] = $test[1];
$myvar["third"] = $test[2];
$myvar["fourth"] = $test[3];
Every array has a key, value pair, if you have an array say:
$myarr = array("a", "b", "c");
then you can access the value "a" as $myarr[0], "b" as $myarr[1] and so on.
In the for loop I am looping through the array with their key and value, this will not only give you the key of the array but also the value associated with that key.
More on Array
Edit:
Improving what Luthando Loot answered:
<?php
$numbers = range(1,4);//generate four numbers
shuffle($numbers);//shuffle them
$test = array();//create array for the results
$words = array("first", "second", "third", "fourth"); //create your array keys
$i = 0;
foreach($numbers as $number){
$test[$words[$i]] = $number;//add your array keys & values
$i++;
}
echo "<pre>";
print_r($test); //show your results
?>
Output:
Array
(
[first] => 4
[second] => 3
[third] => 2
[fourth] => 1
)
use this way
$numbers[0];
$numbers[1];
$numbers[2];
$numbers[3];
Firstly make an array of keys as
$key = ['first','second','third','fourth'];
And then you can simply use array_combine as
$numbers = range(1,4);
shuffle($numbers);
$key = ['first','second','third','fourth'];
$result = array_combine($key,$numbers);
Demo
I have 2 arrays - the first one is output first in full. The 2nd one may have some values that were already used/output with the first array. I want to "clean up" the 2nd array so that I can output its data without worrying about showing duplicates. Just to be sure I have the terminology right & don't have some sort of "array within an array", this is how I access each one:
1st Array
$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem) {
echo $firstResponseItem['samecolumnname']; // Don't care if it's in 2nd array
}
2nd Array
while( $secondResponseRow = $dbRequest->fetch_assoc() ){
$secondResponseArray = array($secondResponseRow);
foreach ($secondResponseArray as $secondResponseItem){
echo $secondResponseItem['samecolumnname']; //This can't match anything above
}
}
Thanks!
For example:
$response_names = array();
$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem)
$response_names[] = $firstResponseItem['samecolumnname'];
while( $secondResponseRow = $dbRequest->fetch_assoc() ){
$secondResponseArray = array($secondResponseRow);
foreach ($secondResponseArray as $secondResponseItem) {
if (!in_array($secondResponseItem['samecolumnname'], $response_names))
$response_names[] = $secondResponseItem['samecolumnname'];
}
}
array_walk($response_names, function($value) { echo $value . '<br />' });
If I understand what you're looking to do and the arrays are in the same scope, this should work.
$secondResponseArray = array($secondResponseRow);
$secondResponseArray = array_diff($secondResponseArray, $firstResponse);
//secondResponseArray now contains only unique items
foreach ($secondResponseArray as $secondResponseItem){
echo $secondResponseItem['samecolumnname'];
}
If you know that the keys of duplicate values will be the same you could use array_diff_assoc to get the items of the first array that aren't in the other supplied arrays.
This code
<?php
$a = array('abc', 'def', 'ghi', 'adg');
$b = array('abc', 'hfs', 'toast', 'adgi');
$r = array_diff_assoc($b, $a);
print_r($a);
print_r($r);
produces the following output
[kernel#~]php so_1.php
Array
(
[0] => abc
[1] => def
[2] => ghi
[3] => adg
)
Array
(
[1] => hfs
[2] => toast
[3] => adgi
)
[kernel#~]