I am doing with Laravel 5. And the problem I am facing is that I have an array in session and now I want to remove a single element from that array and for the sake I am using array_diff function.
When I get array from session it's in the form like:
["4","5","6"]
But when I try to remove element '5' from array it deforms the array and the result then is:
{"0":"4","2":"6"}
My code is:
array_diff($arr, array(5))
The result is same with unset([$index]) also.
The real code:
Session::push('compare.products', $id);
$compare = Session::get('compare');
if(($key = array_search($id, $compare['products'])) !== false) {
unset($compare['products'][$key]);
return $compare['products'];
}
If you want to keep correct indexes you have to call array_values after the unset.
In your case, it will be :
Session::push('compare.products', $id);
$compare = Session::get('compare');
if(($key = array_search($id, $compare['products'])) !== false) {
unset($compare['products'][$key]);
return array_values($compare['products']);
}
In a general case, it's :
$array = array(0, 1, 2, 3);
unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */
https://stackoverflow.com/a/369761/4682796
Related
Is it possible to search an array for a given value and return all the indexes at which the value was found? So for this array:
["Red","Green","Red","Blue"]
I need
[0,2]
with regard to a search for "Red". Searching for "Yellow" in this case would return an empty array.
You can use like this:
$array = ["Red","Green","Red","Blue"];
$output = array_keys($array, "Red");
The $output will be [0,2]
I think this should work:
$input = ["Red","Green","Red","Blue"];
$x = "Red";
$keys = array_keys(array_filter($input, function ($v) use ($x) { return $v === $x;}));
You can iterate the array with foreach:
foreach($input_arr as $key => $value){
if($value == 'Red'){
needed_key_arr[] = $key;
}
}
Also, if you can have an array of values you what to search use:
$lookup_arr = ['Red', 'Green'];
foreach($input_arr as $key => $value){
if(in_array($value, $lookup_arr)){
needed_key_arr[] = $key;
}
}
$arr = ["Red","Green","Red","Blue"];
$valueToSearchFor = ["Red"];
$keys = array_keys(array_filter($arr, function ($val1) use ($valueToSearchFor) { // filter the first array
return array_filter($valueToSearchFor, function ($val) use ($val1) { // use the first array's value
return $val == $val1; // compare them and then return them
});
}));
var_dump($keys) // array(2) { [0]=> int(0) [1]=> int(2) }
First we filter the array then take the values from the first filter to another filter then we match the arrays and we return them. This works for multiple values too.
$arr = ["Red","Green","Red","Blue"];
$valueToSearchFor = ["Red", "Blue"];
$keys = array_keys(array_filter($arr, function ($val1) use ($valueToSearchFor) {
return array_filter($valueToSearchFor, function ($val) use ($val1) {
return $val == $val1;
});
}));
var_dump($keys) // array(3) { [0]=> int(0) [1]=> int(2) [2]=> int(3) }
i have array
Example :
array(3) { [0]=> string(6) "{what}" [1]=> string(5) "[why]" [2]=> string(5) "(how)" }
and then how to take array with specific char ("{") ?
Is my understanding here correct? You want to get items in array that has a "{" Character. Then why not just loop over it and check the item if it has that character and push it in a new array.
$array_with_sp_char = array();
foreach ($arr_items as $item) {
if (strpos($item, '{') !== FALSE) {
array_push($array_with_sp_char, $item);
}
}
Just iterate through your array and filter out the values you are interested in, in your case i guess it's the values that contain the Char "{"
A possible implementation:
$result = array_filter($your_array, function($value) {
return preg_match('/{/', $value);
});
Use a combination of array_filter and strpos:
$array = [
"{what}",
"[why]",
"(how)"
];
$array = array_filter($array, function($value) {
return strpos($value, '{') !== false;
});
print_r($array);
That will give you:
Array
(
[0] => {what}
)
I try to build an array. I don't wanna write something like $array[3][5][8] = []. Because the count of the first Array can change, here it's 3 but it also can be like 9 or 12. Also the values can change, but they are always unique numbers. I hope someone knows a better way. Thank you.
// First Array, which I have. The count and the content can change.
array(3) {
[0]=>
string(1) "3"
[1]=>
string(1) "5"
[2]=>
string(1) "8"
}
// Second Array, thats the goal.
array(1) {
[3]=>
array(1) {
[5]=>
array(1) {
[8]=>
array(0) {
}
}
}
}
This code will solve your problem:
$array = [3,5,8,9]; // your first array
$newArray = null;
foreach ($array as $value) {
if($newArray === null) {
$newArray[$value] = [];
$ref = &$newArray[$value];
}
else {
$ref[$value] = [];
$ref = &$ref[$value];
}
}
$newArray - holds the result you wanted
$array1=array(3,5,8);
$array2=array();
for($i=count($array1);$i>0;$i--){
$temp=array();
$temp[$array1[$i-1]]=$array2;
$array2=$temp;
}
$subject is the reference to the array you are currently in.
$array is the main root array that you obtain in the end.
$input is the input int array.
$subject = $array = [];
foreach($input as $key){
$subject[$key] = []; // create empty array
$subject =& $subject[$key]; // set reference to child
// Now $subject is the innermost array.
// Editing $subject will change the most nested value in $array
}
I have an array in PHP and I don't know how to delete all the elements from every array element from certain character on, icluding that character. Is there a way to do this?
array(1092) {
["Piper;Rosii;Sare;Test;Vinete#####Piper ->Negru;Rosii ->Călite;Sare ->De masă, grunjoasă;Vinete ->Prăjite"]=>
int(124)
}
In my example I want to delete all text from "#####", including "#####" to the end, foreach array element. Is this possible? Or is there a PHP function for this?
UPDATE
My result should look like this:
array(1092) {
["Piper;Rosii;Sare;Test;Vinete]=>
int(124)
}
You can use array_walk to apply the substr and strpos to each element:
$array = [
'23845637;54634;345;3453345;#####morestuff',
'234234#####34596078345j34534534',
'34343245dfg#####asdfsadf;23452345;sdfsdf;345345'
];
array_walk($array, function(&$value, $key) {
$value = substr($value, 0, strpos($value, '#####'));
});
var_dump($array);
Will result in:
array(3) {
[0]=>
string(27) "23845637;54634;345;3453345;"
[1]=>
string(6) "234234"
[2]=>
string(11) "34343245dfg"
}
This will modify the original array.
For each element in the array, we search for the position of '#####' in the string and only take the part from 0 to the position in the string where '#####' occurs.
This will do that by looping through the array exploding the key by ##### and adding it to a new array. I did it in a loop in case your array is bigger than 1
<?php
$oldArray = array("Piper;Rosii;Sare;Test;Vinete#####Piper ->Negru;Rosii ->Călite;Sare ->De masă, grunjoasă;Vinete ->Prăjite" => 124);
$newArray = array();
foreach ($oldArray as $key => $row) {
$newKey = explode('#####', $key);
$newArray[$newKey[0]] = $row;
}
var_dump($newArray);
You can use substr and strpos to add the new entry and then unset the old entry in the array like this example:
$array = array(
"Piper;Rosii;Sare;Test;Vinete#####Piper ->Negru;Rosii ->Călite;Sare ->De masă, grunjoasă;Vinete ->Prăjite" => 124
);
foreach ($array as $key => $value) {
$array[substr($key, 0, strpos($key, '#####'))] = $value;
unset($array[$key]);
}
var_dump($array);
Will result in:
array(1) {
["Piper;Rosii;Sare;Test;Vinete"]=>
int(124)
}
I want to create an array like below
array(2) {
[0]=>
array(2) {
[0]=>
int(1)
[1]=>
int(0)
}
[1]=>
array(2) {
[0]=>
int(2)
[1]=>
int(0)
}
}
Here first element of the inner array will be incremental and second element will always be 0. The outer array length should be 30. I spent a lot of of time on it but couldn't solve it by my one.
Can any one of you help me ?
Thanks
You could do it using array_map() and range():
$o = array_map(function($a) { return array($a, 0); }, range(1, 30));
Demo
The array_fill() function creates an array where all elements are identical. You're asking for an array where the elements aren't all identical, so it's not something you can create simply by using array_fill()....
$array = array_fill(0, 2, array_fill(0, 2, 0));
array_walk($array, function(&$value, $key) { $value[0] = $key+1; });
Maybe you want something like this?
<?php
function initArray() {
$array = array();
for ($i = 1; $i <= 30; $i++) {
$array[] = array($i, 0);
}
return $array;
}
// now call the initArray() function somewhere you need it
$myFancyArray = initArray();
?>