PHP: Ignore key and extract value of an array - php

I have a function that returns an array where the value is an array like below: I want to ignore the key and extract the value directly. How can I do this without a for loop? The returned function only has one key but the key (2 in this case) can be a variable
Array ( [2] => Array ( [productID] => 1 [offerid]=>1)
Expected result:
Array ( [productID] => 1 [offerid]=>1)

There're at least 3 ways of doing this:
Use current function, but be sure that array pointer is in the beginning of your array:
$array = Array (2 => Array ( 'productID' => 1, 'offerid' => 1));
$cur = current($array);
var_dump($cur, $cur['offerid']);
Next is array_values function, which will give you array of values with numeric keys, starting with 0
$array = Array ( 2 => Array ( 'productID' => 1, 'offerid' => 1));
$av = array_values($array);
var_dump($av[0], $av[0]['offerid']);
And third option is use array_shift, this function will return first element of array, but be careful as it reduces the original array:
$array = Array ( 2 => Array ( 'productID' => 1, 'offerid' => 1));
$first = array_shift($array);
var_dump($first, $first['offerid']);

If you want to get the current value of an array, you can use current() assuming the array pointer is in the correct position. If there is only one value, then this should work fine.
http://php.net/manual/en/function.current.php

I think Devon's answer will work for you , but if not your can try
$arr = array_column($arr, $arr[2]);
if you need always the second index of your master array, if you need all index use
array_map(),
something like array_map('array_map', $arr); should work.

Related

Get First element in array as array with corresponding key

Get First element in array as array with corresponding key
For example,
An
Array
(
[Actor] => 1
[Producer] => 1
[Director] => 2
)
I want to get first element with its corresponding key
Array
(
[Actor] => 1
)
How can it be done without looping using some array functions ?
array_slice($arr,0,1), array_splice($arr,0,1);, or list($key,$value)=each($arr) may interest you to solve this problem.
Alternatively, use list() and each() to get the first element:
list($key, $val) = each($arr);
Something like this:
$array = ('actor' => 1, 'producer' => 1, 'director' => 2);
$firstKey = key($array);
$newArray = array();
$newArray[$firstKey] = $array[$firstKey];
var_dump($newArray);

Array_unshift like function that returns the array

is there a built in function in php that prepends an element to an array, and returns the new array?
instead of returning the new length of the array?
You could use
array_merge()
For example
$resultingArray = array_merge(array($newElement), $originalArray);
Next to array_merge, if there ain't any duplicate keys, you can do:
$array = array('a' => 'A');
$append = array('b' => 'hello');
$array = $append + $array;
Gives:
Array
(
[b] => hello
[a] => A
)
The plus is the array union operatorĀ­Docs.
There's no built-in which does it, but it's simple enough to wrap it:
function my_unshift($array, $var) {
array_unshift($array, $var);
return $array;
}
This isn't necessary though, because array_unshift() operates on an array reference so the original is modified in place. array_push(), array_pop(), array_shift() all also operate on a a reference.
$arr = array(1,2,3);
array_unshift($arr, 0);
// No need for return. $arr has been modified
print_arr($arr);
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)

Remove Values from PHP Array if Present

I have the following PHP array:
Array
(
[0] => 750
[1] => 563
[2] => 605
[3] => 598
[4] => 593
)
I need to perform the following action on the array using PHP:
Search the array for a value (the value will be in a
variable; let's call it $number). If the value
is present in the array, remove it.
If someone could walk me through how to do that, it would be much appreciated.
Note: If it makes it any easier, I can form the array so the keys are the same as the values.
$array = array_unique($array) // removes dupicate values
while(false !== ($num = array_search($num, $array))){
unset($array[$num]);
}
$max = max($array);
will search for all keys with value $num and unset them
lets say your $array
$array = array_unique($array) // removes dupicate values
$array = arsort($array)
$variable = $array[0] // the maximum value in the array, and place it in a variable.
$key = array_search($array, $number);
if($key){
unset($array[$key]) // Search array for a value, value is present in array, remove it.
}
array_search() and unset() seems a good method for your sample data in your question. I'll just show a different way for comparison's sake (or in case your use case is slightly different from what you have posted here).
Methods: (Demo)
$array=[750,563,605,598,593];
// if removing just one number apply the number as an array element
$number=605;
var_export(array_diff($array,[$number]));
// if you are performing this task with more than one $number, make $numbers=array() and do the same...
$numbers=[605,563]; // order doesn't matter
var_export(array_diff($array,$numbers));
// if you need to re-index the output array, use array_values()...
$numbers=[605,563]; // order doesn't matter
var_export(array_values(array_diff($array,$numbers)));
Output:
array (
0 => 750,
1 => 563,
3 => 598,
4 => 593,
)
array (
0 => 750,
3 => 598,
4 => 593,
)
array (
0 => 750,
1 => 598,
2 => 593,
)

how to use array_push when pushing both key and value in PHP

I have an empty array. I am able to push values using
array_push($list, item[0]);
But how do I push both key and value.
array_push($list[$key], $item[0])
this does not work.
$list['key']=$item[0];
should work.
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
If you want to maintain the key => value pairs you could use array_merge function.
$arr1 = array('apple' => 'fruit', 'banana' => 'fruit');
$arr2 = array('turnip' => 'vegetable', 'mushroom' => 'other');
$newArray = array_merge($arr1,$arr2)
This will return:
Array
(
[apple] => fruit
[banana] => fruit
[turnip] => vegetable
[mushroom] => other
)
But if two keys are the same in two arrays the one in the first array will be overwritten by the value in the second.

Find the key of a corresponding array value

I have an array like this. What i want is to get the value of the index for specific values. ie, i want to know the index of the value "UD" etc.
Array
(
[0] => LN
[1] => TYP
[2] => UD
[3] => LAG
[4] => LO
)
how can i do that??
array_search function is meant for that usage
snipet:
$index = array_search('UD', $yourarray);
if($index === false){ die('didn\'t found this value!'); }
var_dump($index);
Use array_search:
$array = array(0 => 'LN', 1 => 'TYP', 2 => 'UD', 3 => 'LAG', 4 => 'LO');
$key = array_search('UD', $array); // $key = 2;
if ($key === FALSE) {
// not found
}
Your best bet is:
array_keys() returns the keys, numeric and string, from the input array.
If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the input are returned.
$array = array(0 => 'LN', 1 => 'TYP', 2 => 'UD', 3 => 'LAG', 4 => 'LO');
print_r(array_keys($array, "UD"));
Array
(
[0] => 2
)
Possible considerations for not using array_search()
array_search() If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.
I suggest array_flip:
$value = "UD";
$new = array_flip($arr);
echo "result: " . $new[$value];
Just a note: some of these array_* functions are substantially more useful in PHP 5.3 with the addition of anonymous functions. You can now do things like:
$values = array_filter($userArray, function($user)
{
// If this returns true, add the current $user object to the resulting array
return strstr($user->name(),"ac");
});
Which will return all elements in our imaginary array of user objects that contain "ac" ("Jack","Jacob") in their name.
This has been possible in the past with create function, or simply by defining a function beforehand, but this syntax make it a lot more accessible.
http://ca2.php.net/manual/en/functions.anonymous.php
$array = Array(0 => LN, 1 => TYP, 2 => UD, 3 => LAG, 4 => LO);
$arrtemp = array_keys($array,'UD');
echo 'Result : '.$arrtemp[0];
I use array_keys to find it.

Categories