PHP - unset array where Key is X and Value is Y - php

I have this type of array,
Array
(
[0] => Array
(
[id] => 0
[fams] => 5
)
[1] => Array --> I want to remove this value using its index, which is "1"
(
[id] => 2
[fams] => 5
)
)
I want to remove that array [1] entirely, using its index, so the condition is - where the ID is match, for example - [id] => 2
Is that possible, to remove a particular value with that specific condition?
and without looping (or any similar method that need to loop the array)
thanks in advance!
FYI - I did try to search around, but, to be honest, I'm not sure what "keyword" do I need to use.
I did try before, but I found, array_search, array_keys - and it seems those 2 are not.
I'm okay, if we need several steps, as long as it did not use "loop" method.
---update
I forgot to mention, that I'm using old PHP 5.3.

array_filter should work fine with PHP 5.3.
The downside of this approach is that array_filter will (internally) iterate over all your array's entries, even after finding the right one (it's not a "short-circuit" approach). But at least, it's quick to write and shouldn't make much of a difference unless you're dealing with very big arrays.
Note: you should definitely upgrade your PHP version anyway!
$array = array (
0 =>
array (
'id' => 0,
'fams' => 5
),
1 =>
array (
'id' => 2,
'fams' => 5
)
);
$indexToRemove = 2;
$resultArray = array_filter($array, function ($entry) use ($indexToRemove) {
return $entry['id'] !== $indexToRemove;
});
Demo: https://3v4l.org/6DXjl

You can use array_search to find the key of a sub-array that has a matching id value (extracted using array_column), and if found, unset that element:
if (($k = array_search(2, array_column($array, 'id'))) !== false) {
unset($array[$k]);
}
print_r($array);
Output:
Array
(
[0] => Array
(
[id] => 0
[fams] => 5
)
)
Demo on 3v4l.org
It should be noted that although there is no explicit loop in this code, array_search and array_column both loop through the array internally.

You can use array_column to make id as index of the sub-array then use unset
$a = array_column($a, null, 'id');//new array id as index
$index = 2;// id to remove
if($a[$index]) unset($a[$index]);
print_r($a);
Working example :- https://3v4l.org/ofMr7

Related

How to change array keys according the it's elements

I need to change array value based on specific value. Take a look at this array below :
Array
(
[0] => Array
(
[id] => 5
[title] =>
[nomor] => 1
)
[1] => Array
(
[id] => 6
[title] =>
[nomor] => 2
)
)
I need to change the array key based on nomor value. How can I do that?
You can use array_column for that (doc) as:
$arr = array_column($arr, null, "nomor");
Live example
The easiest way is to simply create a new array, loop through your existing one, and save each elements into the new one with the proper key.
foreach($array as $element) {
$formatted_array[$element['nomor']] = $element;
}
Here is a working fiddle:
https://3v4l.org/PlbJ1
Edit: Keep in mind though, if multiple elements have the same value as "nomor", the latest will override the previous one.
Edit 2: Per the other answer, PHP's array_column function seems to do this simpler.

PHP - Store an array returned by a function in an already existing array, one by one

Very simplified example:
function returnArray() {
return array('First','Second','Third');
}
$arr = array('hello','world');
$arr[] = returnArray();
print_r($arr);
I was (wrongly) expecting to see $arr containing 5 elements, but it actually contains this (and I understand it makes sense):
Array
(
[0] => hello
[1] => world
[2] => Array
(
[0] => First
[1] => Second
[2] => Third
)
)
Easily enough, I "fixed" it using a temporary array, scanning through its elements, and adding the elements one by one to the $arr array.
But I guess/hope that there must be a way to tell PHP to add the elements automatically one by one, instead of creating a "child" array within the first one, right? Thanks!
You can use array_merge,
$arr = array_merge($arr, returnArray());
will result in
Array
(
[0] => hello
[1] => world
[2] => First
[3] => Second
[4] => Third
)
This will work smoothly here, since your arrays both have numeric keys. If the keys were strings, you’d had to be more careful (resp. decide if that would be the result you want, or not), because
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
You are appending the resulting array to previously created array. Instead of the use array merge.
function returnArray() {
return array('First','Second','Third');
}
$arr = array('hello','world');
$arr = array_merge($arr, returnArray());
print_r($arr);

Associative Array display not working

I am trying to call an associative array and I am confused why this would not work.
if I print_r($test); it shows the following:
Array(
[e7a36fadf2410205f0768da1b61156d9] => Array(
[rowid] => e7a36fadf2410205f0768da1b61156d9
[id] => 3
[qty] => 1
[price] => 20
[name] => test
[options] => Array(
[permName] => large
)
[subtotal] => 20
)
)
but if I do $test[0]["rowid"]; it gives the following error Message: Undefined offset: 0
I am still a php newbie but from what I have learned about arrays so far this should work. Any ideas?
Thanks
Your array is associative so $test[0] doesn't exist.
$test['e7a36fadf2410205f0768da1b61156d9']['rowid']
If you want to get the first element without referencing the key you can use reset($test)
$first_element = reset($test);
$first_element['row_id'];
The two examples are functionality identical.
Your outter array seems to have the key "e7a36fadf2410205f0768da1b61156d9" - its not indexed numerically.
So you should use
$test["e7a36fadf2410205f0768da1b61156d9"]["rowid"]
You can also use array_keys if you want to find out what the first non-numerical key is
You either can use key $test['e7a36fadf2410205f0768da1b61156d9']['rowid'] as [Mike B suggested][1]. Or get first element of array with [reset()`]2:
$element = reset( $test);
$element['rowid'];
Or use array_keys() if you will need to work with those keys later (you can always get current key with key()):
$keys = array_keys( $test);
$test[ $keys[0]]['rowid'];
And if you need to browse all records in test just use foreach:
foreach( $test as $key => $item){
$item['rowid'];
}

How to delete element and also shift the $key in array

I have an array looks like
Array
(
[0] => 1213059
[1] => 1213063
[2] =>
[3] =>
[4] => 1213072
)
I would like to make it as following:
Array
(
[0] => 1213059
[1] => 1213063
[2] => 1213072
)
Is there anyone can help me?
Many thanks
Use array_filter
Check demo here:
array_values(array_filter($your_array)); to keep your keys numerically .
array_filter will remove all elements that evaluate to false:
$array = array_filter($array);
I don't think answers above give correct fields order, as it was asked. If you only want to remove some fields from array and leave keys order untouched you could do it with
array_filter($arr) or with unset($arr[$i])
But if you want to get new order of keys, so there is no "holes", in above example to set key 4 to key 2 as keys 2 and 3 are unset, you have to use
ksort($arr)
Here is a complete example:
$arr=array(1,1,3,2,0);
print_r($arr);
echo '<br>';
unset($arr[2]);
ksort($arr);
print_r($arr);
$arr=array_values($arr);#EDITED
ksort($arr) knows not to sort array as it should, so just in case add $arr=array_values($arr); on the end #EDITED
PHP reference of ksort() is on link.
You may use this workaround.
Define this function somewhere:
function removeArrElement($inArr, $elementNr) {
for ($i = $elementNr; $i < count($inArr) - 1; $i++) {
$inArr[$i] = $inArr[$i + 1];
}
unset($inArr[count($inArr) - 1]);
return $inArr;
}
And then, when you want to remove the specific element from $yourArray, do this:
$yourArray = removeArrElement($yourArray, $nthElement);
I feel it's not the most efficient way to do this, but it works fine.

PHP Aligning Array Key Values

I've Googled it for two days, and tried looking at the PHP manual, and I still can't remember that function that aligns the key values for PHP arrays.
All I'm looking for is the function that takes this:
Array
(
[0] => 1
[3] => 2
[4] => 3
[7] => 4
[9] => 5
)
And converts it into this:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Basically, the array is first sorted by key (their values attached to them stay with them), then all the keys are set to all the counting numbers, consecutively, without skipping any number (0,1,2,3,4,5,6,7,8,9...). I saw it being used with ksort() a few months ago, and can't see to remember or find this elusive function.
Well, you see, this one is hard, because the general description on the PHP array functions page does not say that this function does what you're looking for.
But you can sort the array using ksort(), and then use this: array_values() . From the page from the PHP manual:
array_values() returns all the values from the input array and indexes numerically the array.
You can use array_merge:
$array = array_merge($array);
It will reindex values with numeric keys.
Update: Using array_values as proposed in #LostInTheCode's answer is probably more descriptive.
function array_reset_index_keys($array)
{
$return = array();foreach($array as $k => $v){$return[] = $v;}return $return;
}
And then use like a regular function, should re index the array
you can also use native functions such as array_values which returns the values of an array into a single dimension array, causing it to be re indexed .

Categories