Convert Array into Key Value Pair array - php

I have a comma separated string which i explode into an array. If the array is of un-known length and i want to make it into a key value pair array where each element in the array has the same key, how do i do this? i'm assuming i'd have to use array_combine? can anyone give me an example using the array bellow? :
for instance:
array([0]=>zebra, [1]=>cow, [2]=>dog, [3]=>monkey, [4]=>ape)
into:
array([animal]=>zebra, [animal]=>cow, [animal]=>dog, [animal]=>monkey, [animal]=>ape)

You can't use the same key for each element in your array. You need a unique identifier to access the value of the array. When you use animal for all, what value should be used? What you can do is to make a 2 dimensional array that you have an array inside an array:
array(
[animals] => array(
[0]=>zebra, [1]=>cow, [2]=>dog, [3]=>monkey, [4]=>ape
)
)
this can be used with $array['animals'][0]
But still you need numbers or unique identifiers to access the values of the array.

Something like this:
$string = 'zebra,cow,dog,monkey,ape';
$array = explode(',', $string);
$arrayReturn['animals'] = $array;
print_r($arrayReturn);

u cant have same key for all the values but u can do this
lets say your string is
$a = 'dog,ant,rabbit,lion';
$ar = explode(',',$a);
$yourArray = array();
foreach($ar as $animals){
$yourArray['animals']=$animals;
}
Now it doesnot matter how long your string is you will have you array as
$yourArray['animals'][0]='dog'
$yourArray['animals'][1]='ant'
....... so on ......

Related

How to get key of an associative array by searching for offset value?

Using this as an example and being aware of key,
$arr = array(
'product1'=>array('color'=>'blue','size'=>'medium'),
'product2'=>array('color'=>'green','size'=>'large'),
'product3'=>array('color'=>'yellow','size'=>'small'),
);
Is there a method for getting any key in multidimensional array by its incremented value?
For example, I'd like to get the key of the third array value in $arr above. $arr[2] would return the value (an array containing yellow/small).
Is there a way to leverage the key function to get any key by its numeric iterator, rather than the key from the "current position"?
Or, is there another built-in function that I am obviously overlooking which would return the key of $arr[2] instead of it's value?
echo getkey($arr[2]);
# returns product3
Just use array_keys function :
$arr = array(
'product1'=>array('color'=>'blue','size'=>'medium'),
'product2'=>array('color'=>'green','size'=>'large'),
'product3'=>array('color'=>'yellow','size'=>'small'),
);
$keys = array_keys($arr);
echo $keys[2];
// shorter version
echo array_keys($arr)[2];
More infos : http://php.net/manual/en/function.array-keys.php
It doesn't seem logical/efficient to generate a new/full array of keys just to select one from it. The other answers are "working too hard".
array_slice() specifically extracts portions of an array based on position rather than key name. This makes it the perfect function for this case.
Better practice would be to only slice away the subarray that you want, then call for its key, like this:
Code: (Demo)
$arr = array(
'product1'=>array('color'=>'blue','size'=>'medium'),
'product2'=>array('color'=>'green','size'=>'large'),
'product3'=>array('color'=>'yellow','size'=>'small'),
);
$key=2;
echo key(array_slice($arr,$key,1)); // [input],[0-indexed position],[number of subarrays]
Output:
product3
You can use array_keys() function:
function getKey($arr, $i) {
if (empty($arr[array_keys($arr)[$i]])) {
return null;
}
// array_keys($arr)[$i] returns original array's key at i position
// if i = 2, array_keys($arr)[$i] = 'product3'
return array_keys($arr)[$i];
}
// echo getKey($arr, 2);
// returns product3

php array_sum returning first value only

I'm fairly new at php, but this seems to be me overlooking something completely basic?
I have some values in a database column, that are comma separated like so:
1,2,3
When I try to get the sum of the values, I expect the echo of array_sum to be 6, but I only get returned the first value ie. "1"
echo $amount; //Gives 1,2,3 etc.
$amount_array = array($amount);
echo array_sum($amount_array); //Only prints "1"
print_r($amount); // shows 1,2,3
print_r($amount_array); // shows Array ( [0] => 1,2,3 )
It's a string not an array, you have to split it using explode function:
$exploded = explode ( "," , $amount_array);
var_dump($exploded);
To use the array_sum the string needs to be converted to an array
You need to use the explode function:
$amount_array = explode(',', $amount);
So you total code should be like this:
$amount_array = explode(',', $amount);
echo array_sum($amount_array);
array_sum() works by adding up the values in an array. You only have one key=>value pair in your array: key 0 with a value of 1,2,3.
If you have a comma-separated list, and want that to be an array, I would use the explode() function to turn the list into the proper key=>value pairs that array_sum() would expect.
Try
$amount_array = explode(',',$amount);
You can not initialize an array the way you intend. You are passing in a comma-separated string, which is just a single argument. PHP doesn't automagically convert that string into separate arguments for you.
In order to convert a comma-separated string into an array of individual values you can break up the string with a function like explode(), which takes a delimiter and a string as its arguments, and returns an array of the delimiter-separated values.
$amount_array = explode( ',', $amount ); // now $amount_array is the array you intended

Unset keys in an array with matching values in another array

How can I unset the keys in one array where the values contained in a second array match the values in the first array?
Actual array:
$fruits = array('Banana','Cherry','Orange','Apple');
Elements I want to remove:
$remove = array('Banana','Apple');
Need to return:
$array = array('Cherry','Orange');
I know it's possible to remove each one with unset, but I'm looking to make it in one line with two array.
Thanks.
Take a look at this function
link
$arrayWithoutTheDesiredElements = array_diff($originalArr, $toRemoveArray)
EDIT:
for your case: $array = array_diff($fruits, $remove);

PHP make N copies of array with functions

In my code I need to make a number of copies of a dummy array. The array is simple, for example $dummy = array('val'=> 0). I would like make N copies of this array and tack them on to the end of an existing array that has a similar structure. Obviously this could be done with a for loop but for readability, I'm wondering if there are any built in functions that would make this more verbose.
Here's the code I came up with using a for loop:
//example data, not real code
$existingArray = array([0] => array('val'=>2),[1] => array('val'=>3) );
$n = 2;
for($i=0;$i<$n;$i++) {
$dummy = array('val'=>0); //make a new array
$existingArray[] = $dummy; //add it to the end of $existingArray
}
To reiterate, I'd like to rewrite this with functions if such functions exist. Something along the lines of this (obviously these are not real functions):
//make $n copies of the array
$newvals = clone(array('val'=>0), $n);
//tack the new arrays on the end of the existing array
append($newvals, $existingArray)
I think you're looking for array_fill:
array array_fill ( int $start_index , int $num , mixed $value )
Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter.
So:
$newElements = array_fill(0, $n, Array('val' => 0));
You do still have to handle the appending of $newElements to $existingArray yourself, probably with array_merge:
array array_merge ( array $array1 [, array $... ] )
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
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.
Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
So:
$existingArray = array_merge($existingArray, $newElements);
This all works because your top-level arrays are numerically-indexed.

Can Indexed Arrays be used as associative arrays?

I know that in PHP an indexed array that looks like:
$array = ("hello", "world")
is the same as an associative array that looks like:
$array = (0 => "hello", 1 => "world");
so my question is if code like this is valid :
$hello = $array[$array["hello"]];
my thinking is that it translates to
$hello = $array[0]
, which will equal
$hello = "hello"
. In other words, will
$array["hello"]
equal 0?
No, you cannot fetch a key of some array element by its value right away... unless you switch keys and values with array_flip:
$arr = array('hello', 'world');
$arr = array_flip($arr);
print $arr['hello']; // 0
Let's walk through the thinking:
$array = ("hello", "world") // This is implicitly indexed by integer.
is the same as:
$array = (0 => "hello", 1 => "world"); // Explicit indexing.
You can verify by doing print_r($array); In either case, the output would show an indexed array. PHP arrays are all associative. Even if you did not specify a key, the values in an array are ordered by integer index numbers.
Now let's take a look at:
so my question is if code like this is valid :
$hello = $array[$array["hello"]];
This is where the code will break. Why?
$array["hello"] is not a valid value. What this is referencing is "the value of the array's list at index "hello".
However, array("hello", "world") does not have an index key of "hello". Rather, it has a value "hello" which has implicitly the key index 0.
Make sure to read up on PHP arrays and understand that:
PHP arrays are all associative; keys can be strings, or if not explicitly set, will be integers.
Associative arrays are in the form of key => value pairs. If you have a key, you can find the value associated with it.
When trying to get a value from a PHP array, the syntax is: $array['key'] or in the case of multidimensionals $array['firstlevelkey']['secondlevelkey'] etc. The value that gets returned would be the value of the key => value pair at that particular key.
I hope this is helpful!
No, since "hello" is not a valid key in $array.
You can check if a key exist using array_key_exists(key,*array*)

Categories