Remove an item from an associative array php - php

How can I remove from this array the current selected language:
$lang = 'en-US';
$languages = array('LANG001' => 'en-US', 'LANG002' => 'es-ES', 'LANG003' => 'fr-CA');
I try with unset($languages[$lang]) without success.
Thanks.

try:
unset($languages[array_search($lang,$languages,true)]);

1) The index in an array expression must be the key, not the value. If you want to delete an element by the value, you have to find its key first.
$key = array_search($lang, $languages);
if ($key) {
unset($languages[$key]);
}
However, this will only remove the first occurrence of the value in the array. If the value can appear multiple times and you want to remove all of them, you can do:
$languages = array_diff($languages, array($lang));

Why do you want to echo specific values in a loop?
You'd use a loop to echo values depending on a pattern or simply every value.
To access variables inside of a loop, you'd do it the same way as everywhere else in a script,
check if the variable exists then echo that specific var.
Simply use
(isset($languages['LANG001']) ? echo $languages['LANG001'] : null);
(isset($languages['LANG002']) ? echo $languages['LANG002'] : null);

Related

Search for an item in inner array

I have an assoc array looking like this (the data comes from user input, this is just an example)
$startingDate = "2020-10-20";
$daysBetween[] = "2020-10-21", "2020-10-22", "2020-10-23";
$endingDate = "2020-10-24";
$eventDates[ID] => [
"startingDate" => $startingDate,
"daysBetween" => $daysBetween,
"endingDate" => $endingDate,
];
How would I look for a specific startingDate for example if I don't want to loop over every ID. Basically I'm looking for a way to do something like $eventDates[*]["startingDate"]
You can achieve this a few different ways, one being array_filter().
$searchFor = '2020-09-20';
$result = array_filter($eventDates, function($v) use ($searchFor) {
return ($v['startingDate'] ?? null) == $searchFor;
});
This returns the array(s) where you match the $searchFor variable with a column startingDate. If you just want the first one, use $result = array_shift($result); to get the first one.
This approach basically filters out any results where the callback doesn't return true. By including use ($searchFor) the variable becomes visible inside the scope of that function, otherwise it would be undefined within that scope.
Live demo at https://3v4l.org/iaT8k
The questioner states that they are looking for a way to do something like
$eventDates[*]["startingDate"]
The PHP equivalent to this is:
foreach ($eventDates as $id => $eventDate) {
//look at $eventDate["startingDate"] and if it matches the criteria do whatever required
//you know the ID (=$id) so you can save/return/use that if needed.
}

How to fix json_decode out put

when in use json_decod with option "JSON_FORCE_OBJECT" its return out put index started with 0 and its true but i need to start the out put index with 1 so how i can fix my problem?
json_encode($request->get('poll_items'), JSON_FORCE_OBJECT)
The output result is and current BUT:
"{"0":"option1","1":"option2","2":"option3"}"
I need to return like this:
"{"1":"option1","2":"option2","3":"option3"}"
Thank you.
An easy solution would be to use array_unshift() and unset():
$array = $request->get('poll_items');
// Add an element to the beginning
array_shift($array, '');
// Unset the first element
unset($array[0]);
Now you're left with an associative array that starts with 1.
Here's a demo
My first question would be why do you need this to be 1 indexed instead of 0?
If this data is consumed outside of your control then you could map the data across to another array and encode that instead. For example:
$newArray = array();
foreach ($request->get('poll_items') as $index => $value) {
$newArray[++$index] = $value
}
$output = json_encode($newArray, JSON_FORCE_OBJECT);
NOTE: ++$index instead of $index++ as the latter will only alter the value after the line has computed.

How add value in the beginning of the array with a key?

I know about function array_unshift(), but that adds to array with a autoincrement key.
For this code:
$messages[$obj_result['from']] = $obj_result;
I need to add value $obj_result in the beginning of the array. So, last added value will be in the beginning of array.
do somthing like this
$array = array("a"=>1,"b"=>2,"d"=>array("e"=>1));
$newArray["c"] = 3;
echo "<pre>";
print_r(array_merge($newArray,$array));
in array_merge first argument will be your that key value pair that you want to add in beginning.
Assuming as an array (with your desire key) you can use operator + :
$messages = obj_result + $messages;
From the manual:
while literal keys won't be touched
So you can just prepend the element, assuming the from key of the $obj_result variable is a string, all the key's will stay the same, while your new element is still on the beginning of the array.

Returning string value in php array

Its a simple problem but i dont remember how to solve it
i have this array:
$this->name = array('Daniel','Leinad','Leonard');
So i make a foreach on it, to return an array
foreach ($this->name as $names){
echo $names[0];
}
It returns
DLL
It returns the first letter from my strings in array.I would like to return the first value that is 'Daniel'
try this one :
foreach ($this->name as $names){
echo $names; //Daniel in first iteration
// echo $names[0]; will print 'D' in first iteration which is first character of 'Daniel'
}
echo $this->name[0];// gives only 'Daniel' which is the first value of array
Inside your loop, each entry in $this->name is now $names. So if you use echo $names; inside the loop, you'll print each name in turn. To get the first item in the array, instead of the loop use $this->name[0].
Edit: Maybe it makes sense to use more descriptive names for your variables.
For example $this->names_array and foreach ( $this->names_array as $current_name ) makes it clearer what you are doing.
Additional answer concerning your results :
You're getting the first letters of all entries, actually, because using a string as an array, like you do, allows you to browse its characters. In your case, character 0.
Use your iterative element to get the complete string everytime, the alias you created after as.
If you only want the first element, do use a browsing loop, just do $this->name[0]. Some references :
http://php.net/manual/fr/control-structures.foreach.php
http://us1.php.net/manual/fr/language.types.array.php

Can items in PHP associative arrays not be accessed numerically (i.e. by index)?

I'm trying to understand why, on my page with a query string,
the code:
echo "Item count = " . count($_GET);
echo "First item = " . $_GET[0];
Results in:
Item count = 3
First item =
Are PHP associative arrays distinct from numeric arrays, so that their items cannot be accessed by index? Thanks-
They can not. When you subscript a value by its key/index, it must match exactly.
If you really wanted to use numeric keys, you could use array_values() on $_GET, but you will lose all the information about the keys. You could also use array_keys() to get the keys with numerical indexes.
Alternatively, as Phil mentions, you can reset() the internal pointer to get the first. You can also get the last with end(). You can also pop or shift with array_pop() and array_shift(), both which will return the value once the array is modified.
Yes, the key of an array element is either an integer (must not be starting with 0) or an associative key, not both.
You can access the items either with a loop like this:
foreach ($_GET as $key => $value) {
}
Or get the values as an numerical array starting with key 0 with the array_values() function or get the first value with reset().
You can do it this way:
$keys = array_keys($_GET);
echo "First item = " . $_GET[$keys[0]];
Nope, it is not possible.
Try this:
file.php?foo=bar
file.php contents:
<?php
print_r($_GET);
?>
You get
Array
(
[foo] => bar
)
If you want to access the element at 0, try file.php?0=foobar.
You can also use a foreach or for loop and simply break after the first element (or whatever element you happen to want to reach):
foreach($_GET as $value){
echo($value);
break;
}
Nope -- they are mapped by key value pairs. You can iterate the they KV pair into an indexed array though:
foreach($_GET as $key => $value) {
$getArray[] = $value;
}
You can now access the values by index within $getArray.
As another weird workaround, you can access the very first element using:
print $_GET[key($_GET)];
This utilizes the internal array pointer, like reset/end/current(), could be useful in an each() loop.

Categories