php update value in multidimensional array not by reference - php

I know that this is a similar question:
Updating a Multidimensional Array in PHP
but is different my problem:
I have a multidimensional array and I want to check if a value inside it is equal another, if tue update value.
I have tried in this way:
$room_id = '1205222__1763659__386572_1';
foreach($cart as $c){
if($c['item_type'] == 'hotel'){
foreach($c as $key => $value){
if(substr($key, 0, 7) == 'room_id'){
if($value == $room_id) {
$c[$key] = '';
}
}
}
}
}
This is an example of my array:
array() {
[0]=>
array() {
["item_type"]=> "hotel"
["room_id_0"]=> "1205222__1763659__386572_1"
["room_id_1"]=> "1205222__1763659__386572_2"
},
[1]=>
array() {
["item_type"]=> "hotel"
["room_id_0"]=> "1205222__1763659__386572_3"
["room_id_1"]=> "1205222__1763659__386572_4"
}
}
I have checked if the conditions work right and yes, but when I make the assignment and after print the array again the array isn't changed.
Can someone help me?
Thanks

this won't work as you are changing $c which is a copy of the array $cart. you would need to get the array key of the first array value and the array key of the second array and then update:
try this
foreach($cart as $a => $c){
if($c['item_type'] == 'hotel'){
foreach($c as $key => $value){
if(substr($key, 0, 7) == 'room_id'){
if($value == $room_id) {
$cart[$a][$key] = '';
}
}
}
}
}

You can call foreach with passing $c by reference, like this:
foreach($cart as &$c){
...
This should let you change the value of the item.
To take it a step further, you could also pass $value by reference, and then change its value by modifying $value:
// Notice &$c
foreach($cart as &$c){
if($c['item_type'] == 'hotel'){
// Notice &$value
foreach($c as $key => &$value){
if(substr($key, 0, 7) == 'room_id'){
if($value == $room_id) {
// Instead of $c[$key]
$value = '';
}
}
}
}
}

Related

Removing array key from multidimensional Arrays php

I have this array
$cart= Array(
[0] => Array([id] => 15[price] => 400)
[1] => Array([id] => 12[price] => 400)
)
What i need is to remove array key based on some value, like this
$value = 15;
Value is 15 is just example i need to check array and remove if that value exist in ID?
array_filter is great for removing things you don't want from arrays.
$cart = array_filter($cart, function($x) { return $x['id'] != 15; });
If you want to use a variable to determine which id to remove rather than including it in the array_filter callback, you can use your variable in the function like this:
$value = 15;
$cart = array_filter($cart, function($x) use ($value) { return $x['id'] != $value; });
There are a lot of weird array functions in PHP, but many of these requests are solved with very simple foreach loops...
$value = 15;
foreach ($cart as $i => $v) {
if ($v['id'] == $value) {
unset($cart[$i]);
}
}
If $value is not in the array at all, nothing will happen. If $value is in the array, the entire index will be deleted (unset).
you can use:
foreach($array as $key => $item) {
if ($item['id'] === $value) {
unset($array[$key]);
}
}

PHP foreach/else issue

foreach($cases['rows'] as $i => $item) {
foreach($array as $key => $val) {
if($item['status'] == $key) {
echo $val;
}
}
}
Right now this code functions, but if $item['status'] != $key it echoes nothing. I've tried to add an else statement after the if statement except it prints it tens of times.
How can I achieve this functionality? I want it to print $item['status'] if $item['status'] != $key
Help is appreciated.
Thanks.
The way I understand the question you have two arrays:
An array containing different abbreviations and their full meaning.
Another multidimensional array containing arrays which again contain status-abbreviations.
To echo the full meaning instead of the abbreviations:
$abbreviations = array('NT' => 'Not taken',
'N/A' => 'Not available');
$data = array(array('status' => 'NT'),
array('status' => 'N/A'));
foreach($data as $item) {
if(array_key_exists($item['status'], $abbreviations)) {
echo $abbreviations[$item['status']] . PHP_EOL;
} else {
echo $item['status'] . PHP_EOL;
}
}
Result:
Not taken
Not available
Try this:
$test = null;
foreach($cases['rows'] as $i => $item) {
foreach($array as $key => $val) {
if($item['status'] == $key) {
echo $val;
}
else {
$test = $val;
}
}
}
if($test != null) {
echo $test//Or whatever you want to display
}
Without more info regarding the type of data in both arrays, I would suggest you to try:
!($item['status'] == $key) deny the correct statement
$item['status'] !== $key try also checking the same type (test this also with the equal statement to see if you get the results you expect)

Resetting position of items in array PHP

I have a string of 7 numbers in an array looks like 4,1,2,56,7,9,10 however sometimes these elements are empty ,,,56,7,9,10 for example. What I would like to do is reorder the array so it looks like 56,7,9,10,,,
try this:
$null_counter = 0;
foreach($array as $key => $val) {
if($val == null) {
$null_counter++;
unset($array[$key]);
}
}
for($x=1;$x<=$null_counter;$x++) {
$array[] = null;
}
Use unset in loop to remove null value and shift the values Up.
foreach($yourarray as $key=>$val )
{
if($yourarray[$key] == '')
{
unset($yourarray[$key]);
}
}

PHP if in array, do something with the value

I am trying to check if a value is in an array. If so, grab that array value and do something with it. How would this be done?
Here's an example of what I'm trying to do:
$the_array = array("buejcxut->10", "jueofi31->20", "nay17dtt->30");
if (in_array('20', $the_array)) {
// If found, assign this value to a string, like $found = 'jueofi31->20'
$found_parts = explode('->', $found);
echo $found_parts['0']; // This would echo "jueofi31"
}
This should do it:
foreach($the_array as $key => $value) {
if(preg_match("#20#", $value)) {
$found_parts = explode('->', $value);
}
echo $found_parts[0];
}
And replace "20" by any value you want.
you might be better off checking it in a foreach loop:
foreach ($the_array as $key => $value) {
if ($value == 20) {
// do something
}
if ($value == 30) {
//do something else
}
}
also you array definitition is strange, did you mean to have:
$the_array = array("buejcxut"=>10, "jueofi31"=>20, "nay17dtt"=>30);
using the array above the $key is the element key (buejcxut, jueofi31, etc) and $value is the value of that element (10, 20, etc).
Here's an example of how you can search the values of arrays with Regular Expressions.
<?php
$the_array = array("buejcxut->10", "jueofi31->20", "nay17dtt->30");
$items = preg_grep('/20$/', $the_array);
if( isset($items[1]) ) {
// If found, assign this value to a string, like $found = 'jueofi31->20'
$found_parts = explode('->', $items[1]);
echo $found_parts['0']; // This would echo "jueofi31"
}
You can see a demo here: http://codepad.org/XClsw0UI
if you want to define an indexed array it should be like this:
$my_array = array("buejcxut"=>10, "jueofi31"=>20, "nay17dtt"=>30);
then you can use in_array
if (in_array("10", $my_array)) {
echo "10 is in the array";
// do something
}

PHP - Grab the first element using a foreach

Wondering what would be a good method to get the first iteration on a foreach loop.
I want to do something different on the first iteration.
Is a conditional our best option on these cases?
Yes, if you are not able to go through the object in a different way (a normal for loop), just use a conditional in this case:
$first = true;
foreach ( $obj as $value )
{
if ( $first )
{
// do something
$first = false;
}
else
{
// do something
}
// do something
}
Even morer eleganterer:
foreach($array as $index => $value) {
if ($index == 0) {
echo $array[$index];
}
}
That example only works if you use PHP's built-in array append features/function or manually specify keys in proper numerical order.
Here's an approach that is not like the others listed here that should work via the natural order of any PHP array.
$first = array_shift($array);
//do stuff with $first
foreach($array as $elem) {
//do stuff with rest of array elements
}
array_unshift($array, $first); //return first element to top
You can simply add a counter to the start, like so:
$i = 0;
foreach($arr as $a){
if($i == 0) {
//do ze business
}
//the rest
$i++;
}
I saw this solution on a blog post in my search result set that brought up this post and I thought it was rather elegant. Though perhaps a bit heavy on processing.
foreach ($array as $element)
{
if ($element === reset($array))
echo 'FIRST ELEMENT!';
if ($element === end($array))
echo 'LAST ELEMENT!';
}
Do note there is also a warning on the post that this will only work if the array values are unique. If your last element is "world" and some random element in the middle is also "world" last element will execute twice.
hm
<?php
$i = 0;
foreach($ar as $sth) {
if($i++ == 0) {
// do something
}
// do something else
}
more elegant.
first = true
foreach(...)
if first
do stuff
first = false
This is also works
foreach($array as $element) {
if ($element === reset($array))
echo 'FIRST ELEMENT!';
if ($element === end($array))
echo 'LAST ELEMENT!';
}
foreach($array as $element) {
if ($element === reset($array))
echo 'FIRST ELEMENT!';
if ($element === end($array))
echo 'LAST ELEMENT!';
}
Here's an example that does not use foreach loop
<?php
// A sample indexed array
$cities = array("London", "Paris", "New York");
echo $cities[0]; // Outputs: London
// A sample associative array
$fruits = array("a" => "Apple", "b" => "Ball", "c" => "Cat");
echo array_values($fruits)["0"]; // Outputs: Apple
?>
What about using key() native php function? which should work fine with all kind of arrays (indexed, associative ) as it will always return the first key no matter if its inside or outside the loop.
$array = array(
'One' => 'value',
'Two' => 'value-2',
'Three' => 'value-3',
);
foreach ( $array as $index => $key ) {
if ( key( $array ) ) {
/**Do something with the first key*/
} else {
/**Do something else*/
}
}
if it indexed array, you have many options you can go through,
for me using counter is always fine and get the correct result all the time.
$array = array(
'One',
'Two',
'Three',
);
$i = 0;
foreach ( $array as $index => $key ) {
if ( $array[ $i ] ) {
/**Do something with the first key*/
} else {
/**Do something else*/
$i++;
}
}
Both should work fine with $key => $value loop and it will only return the first key.
Also I would like to add something, You can always archive your target in scripting with hundreds of different way, Its all about the way you want to use in this situation.

Categories