I have one array and i want to keep only blank values in array in php so how can i achieve that ?
My array is like
$array = array(0=>5,1=>6,2=>7,3=>'',4=>'');
so in result array
$array = array(3=>'',4=>'');
I want like this with existing keys.
You can use array_filter.
function isBlank($arrayValue): bool
{
return '' === $arrayValue;
}
$array = array(0 => 5, 1 => 6, 2 => 7, 3 => '', 4 => '');
var_dump(array_filter($array, 'isBlank'));
use for each loop like this
foreach($array as $x=>$value)
if($value=="")
{
$save=array($x=>$value)
}
if you want print then use print_r in loop
there is likely a fancy built in function but I would:
foreach($arry as $k=>$v){
if($v != ''){
unset($arry[$k]);
}
}
the problem is; you are not using an associative array so I am pretty sure the resulting values would be (from your example) $array = array(0=>'',1=>''); so you would need to:
$newArry = array();
foreach($arry as $k=>$v){
if($v == ''){
$newArry[$k] = $v;
}
}
Related
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, ', ');
This question already has answers here:
Finding the subsets of an array in PHP
(5 answers)
Closed 7 years ago.
I will do my best to explain this idea to you. I have an array of values, i would like to know if there is a way to create another array of combined values. So, for example:
If i have this code:
array('ec','mp','ba');
I would like to be able to output something like this:
'ec,mp', 'ec,ba', 'mp,ba', 'ec,mp,ba'
Is this possible? Ideally i don't want to have duplicate entries like 'ec,mp' and 'mp,ec' though, as they would be the same thing
You can take an arbitrary decision to always put the "lower" string first. Once you made this decision, it's just a straight-up nested loop:
$arr = array('ec','mp','ba');
$result = array();
foreach ($arr as $s1) {
foreach ($arr as $s2) {
if ($s1 < $s2) {
$result[] = array($s1, $s2);
}
}
}
You can do it as follows:
$arr = array('ec','mp','ba', 'ds', 'sd', 'ad');
$newArr = array();
foreach($arr as $key=>$val) {
if($key % 2 == 0) {
$newArr[] = $val;
} else {
$newArr[floor($key/2)] = $newArr[floor($key/2)] . ',' . $val;
}
}
print_r($newArr);
And the result is:
Array
(
[0] => ec,mp
[1] => ba,ds
[2] => sd,ad
)
Have you looked at the function implode
<?php
$array = array('ec','mp','ba');
$comma_separated = implode(",", $array);
echo $comma_separated; // ec,mp,ba
?>
You could use this as a base for your program and what you are trying to achieve.
I have an array as such:
$array = ["1","0","0","1","1"]
//replace with
$newArray = ["honda","toyota","mercedes","bmw","chevy"]
// only if the original array had a value of "1".
// for example this is my final desired output:
$newArray = ["honda","0","0","bmw","chevy"]
I want to change each value in a specific order IF and only if the array value is equal to "1".
For example the values, "honda", "toyota", "mercedes", "bmw", "chevy" should only replace the array values if the value is "1" otherwise do not replace it and they must be in the right position for example the first element in the array must only be changed to honda, not toyota or any of the other values.
I know I must iterate through the array and provide an if statement as such:
foreach($array as $val) {
if($val == 1){
//do something
} else {
return null;
}
}
Please guide me in the right direction and describe how to replace the values in order, so that toyota cannot replace the first array value only the second position.
You can so something like this - iterating over the array by reference and replacing when the value is 1 (string) and the value in the replace array exists:
foreach($array as $key => &$current) {
if($current === '1' && isset($replace[$key]))
$current = $replace[$key];
}
Output:
Array
(
[0] => honda
[1] => 0
[2] => 0
[3] => bmw
[4] => chevy
)
As per your comment, to output an imploded list of the cars that do have values, you can do something like this - filtering out all zero values and imploding with commas:
echo implode(
// delimiter
', ',
// callback - filter out anything that is "0"
array_filter($array, function($a) {
return $a != '0';
})
);
Currently, our if is asking if $val is true (or if it exists) while your numeric array's values are strings.
Try this:
$array = ["1","0","0","1","1"]
$newArray = ["honda","toyota","mercedes","bmw","chevy"]
foreach($array as $key => $val) {
if($val === '1'){ // if you only want honda
$array[$key] = $newArray[$key];
} else {
return null;
}
}
PHP Code
$array = array("1","0","0","1","1");
$newArray = array("honda","toyota","mercedes","bmw","chevy");
foreach($array as $key => $val) {
if($val === '1')
$array[$key] = $newArray[$key];
}
Would produce the answer you're looking for
Is there any way that I can remove the successive duplicates from the array below while only keeping the first one?
The array is shown below:
$a=array("1"=>"go","2"=>"stop","3"=>"stop","4"=>"stop","5"=>"stop","6"=>"go","7"=>"go","8"=>"stop");
What I want is to have an array that contains:
$a=array("1"=>"go","2"=>"stop","3"=>"go","7"=>"stop");
Successive duplicates? I don't know about native functions, but this one works. Well almost. Think I understood it wrong. In my function the 7 => "go" is a duplicate of 6 => "go", and 8 => "stop" is the new value...?
function filterSuccessiveDuplicates($array)
{
$result = array();
$lastValue = null;
foreach ($array as $key => $value) {
// Only add non-duplicate successive values
if ($value !== $lastValue) {
$result[$key] = $value;
}
$lastValue = $value;
}
return $result;
}
You can just do something like:
if(current($a) !== $new_val)
$a[] = $new_val;
Assuming you're not manipulating that array in between you can use current() it's more efficient than counting it each time to check the value at count($a)-1
So far, if I have to loop through a multidimensional array, I use a foreach loop for each dimension.
e.g for two dimensions
foreach($array as $key=>$value)
{
foreach($value as $k2=>$v2)
{
echo
}
}
What do I do when I don't know the depth of the array? ie the depth is variable.
The only thing I can think of is to code a whole stack of loops and to break the loop if the next value is not an array.This seems a little silly.
Is there a better way?
Yes, you can use recursion. Here's an example where you output all the elements in an array:
function printAll($a) {
if (!is_array($a)) {
echo $a, ' ';
return;
}
foreach($a as $v) {
printAll($v);
}
}
$array = array('hello',
array('world',
'!',
array('whats'),
'up'),
array('?'));
printAll($array);
What you should always remember when doing recursion is that you need a base case where you won't go any deeper.
I like to check for the base case before continuing the function. That's a common idiom, but is not strictly necessary. You can just as well check in the foreach loop if you should output or do a recursive call, but I often find the code to be harder to maintain that way.
The "distance" between your current input and the base case is called a variant and is an integer. The variant should be strictly decreasing in every recursive call. The variant in the previous example is the depth of $a. If you don't think about the variant you risk ending up with infinite recursions and eventually the script will die due to a stack overflow. It's not uncommon to document exactly what the variant is in a comment before recursive functions.
You can do the below function for loop-through-a-multidimensional-array-without-knowing-its-depth
// recursive function loop through the dimensional array
function loop($array){
//loop each row of array
foreach($array as $key => $value)
{
//if the value is array, it will do the recursive
if(is_array($value) ) $array[$key] = loop($array[$key]);
if(!is_array($value))
{
// you can do your algorithm here
// example:
$array[$key] = (string) $value; // cast value to string data type
}
}
return $array;
}
by using above function, it will go through each of the multi dimensional array, below is the sample array you could pass to loop function :
//array sample to pass to loop() function
$data = [
'invoice' => [
'bill_information' => [
'price' => 200.00,
'quantity' => 5
],
'price_per_quantity' => 50.00
],
'user_id' => 20
];
// then you can pass it like this :
$result = loop($data);
var_dump($result);
//it will convert all the value to string for this example purpose
You can use recursion for this problem:
Here is one example
$array = array(1 => array(1 => "a", 2 => array(1 => "b", 2 => "c", 3 => array(1 => "final value"))));
//print_r($array);
printAllValues($array);
function printAllValues($arr) {
if(!is_array($arr)) {
echo '<br />' . $arr;
return;
}
foreach($arr as $k => $v) {
printAllValues($v);
}
}
It will use recursion to loop through array
It will print like
a
b
c
final value
Simple function inside array_walk_recursive to show the level of nesting and the keys and values:
array_walk_recursive($array, function($v, $k) {
static $l = 0;
echo "Level " . $l++ . ": $k => $v\n";
});
Another one showing use with a reference to get a result:
array_walk_recursive($array, function($v) use(&$result) {
$result[] = $v;
});
Based on previous recursion examples, here is a function that keeps an array of the path of keys a value is under, in case you need to know how you got there:
function recurse($a,$keys=array())
{
if (!is_array($a))
{
echo implode("-", $keys)." => $a <br>";
return;
}
foreach($a as $k=>$v)
{
$newkeys = array_merge($keys,array($k));
recurse($v,$newkeys);
}
}
recurse($array);