How do I access the following array in PHP:
$Record = Array ( [0] => 1 [1] => 1 [2] => 1);
I have tried
echo $Record[0];
But no luck :(
To initialize an array (you don't need an associative array, if your keys are just the actual indices) use:
$record = array(1, 1, 1);
Then you can access the first element via:
$first = $record[0];
Try
$Record = array( 0 => 1, 1 => 1, 2 => 1);
or even
$Record = array(1,1,1);
and then
echo $Record[0];
Keep in mind that print_r shows you some form of representation of the array. so this code:
$record1 = array(1,1,1);
print_r($record1);
will output:
Array
(
[0] => 1
[1] => 1
[2] => 1
)
$Record = Array ( 1, 1, 1 );
your array has wrong syntax
just a guess, but you can try something like that:
$pattern = "|\[(\d+)\] => (\d+)|";
preg_replace_callback(
$pattern,
"add_to_array",
$text);
and write a function 'add_to_array' to add to your array, get the index by $matches[1] and the value by $matches[2]!
Related
Array
(
)
Array
(
)
Array
(
[0] => 14
)
Array
(
[0] => 14
)
Array
(
[0] => 14
)
Array
(
[0] => 14
)
Array
(
[0] => 14
)
Array
(
[0] => 14
[1] => 12
)
I want this array
Array
(
[0] => 14
[1] => 12
)
Here is my code:
$colorarray = array();
foreach($catIds as $catid){
$colorarray[] = $catid;
}
Need to get unique array values
Thanks
You can use call_user_func_array with array-merge for flatten your array and then use array-unique as:
$res = call_user_func_array('array_merge', $arr);
print_r(array_unique($res)); // will give 12 and 14
Live example 3v4l
Or as #Progrock suggested: $output = array_unique(array_merge(...$data)); (I like that syntax using the ...)
You can always do something like this:
$colorarray = array();
foreach($catIds as $catid){
if(!in_array($catid, $colorarray) {
$colorarray[] = $catid;
}
}
But also this has n*n complexity, So if your array is way too big, it might not be the most optimised solution for you.
You can do following to generate unique array.
array_unique($YOUR_ARRAY_VARIABLE, SORT_REGULAR);
this way only unique value is there in your array instead of duplication.
UPDATED
This is also one way to do same
<?php
// define array
$a = array(1, 5, 2, 5, 1, 3, 2, 4, 5);
// print original array
echo "Original Array : \n";
print_r($a);
// remove duplicate values by using
// flipping keys and values
$a = array_flip($a);
// restore the array elements by again
// flipping keys and values.
$a = array_flip($a);
// re-order the array keys
$a= array_values($a);
// print updated array
echo "\nUpdated Array : \n ";
print_r($a);
?>
Reference link
Hope this will helps you
I have updated your code please check
$colorarray = array();
foreach($catIds as $catid){
$colorarray[$catid] = $catid;
}
This will give you 100% unique values.
PHP: Removes duplicate values from an array
<?php
$fruits_list = array('Orange', 'Apple', ' Banana', 'Cherry', ' Banana');
$result = array_unique($fruits_list);
print_r($result);
?>
------your case--------
$result = array_unique($catIds);
print_r($result);
You can construct a new array of all values by looping through each sub-array of the original, and then filter the result with array_unique:
<?php
$data =
[
[
0=>13
],
[
0=>13
],
[
0=>17,
1=>19
]
];
foreach($data as $array)
foreach($array as $v)
$all_values[] = $v;
var_export($all_values);
$unique = array_unique($all_values);
var_export($unique);
Output:
array (
0 => 13,
1 => 13,
2 => 17,
3 => 19,
)array (
0 => 13,
2 => 17,
3 => 19,
)
When I execute the code below:
Code:
<?php
$data = array();
$jim = array('Jim'=>1);
$bob = array('Bob'=>1);
$data['abc'][] = $jim;
$data['abc'][] = $bob;
print_r($data);
?>
I receive the following output:
Array
(
[abc] => Array
(
[0] => Array
(
[Jim] => 1
)
[1] => Array
(
[Bob] => 1
)
)
)
What I am expecting is the following output:
Array
(
[abc] => Array
(
[Jim] => 1
[Bob] => 1
)
)
How can I achieve this? To rephrase the question, how can I keep it to a single sub-array per a supplied key?
$data = array();
$jim = array('Jim'=>1);
$bob = array('Bob'=>1);
$data['abc'] = array_merge($jim, $bob);
print_r($data);
You are creating array ($data['abc']) which contains an array ([]) of arrays($jim, $bob)
It's the same as writing:
$data['abc'][0] = array('jim' => 1);
$data['abc'][1] = array('bob' => 1);
What you want is probably:
$data['abc'] = array();
$data['abc'] = array_merge($data['abc'], $jim, $bob);
Jim and Bob are array indexes by your own declaration, you have to change them first
<?php
$data = array();
$data['abc']["Jim"] =1;
$data['abc']["Bob"] = 2;
print_r($data);
?>
Demo
I have a very simple array like this:
Array ( [friend_id] => 180 [user_id] => 175 )
What I want to do is just to switch the values, in order to be come this:
Array ( [friend_id] => 175 [user_id] => 180 )
Is there any elegant NON STATIC way in PHP to do it?
you can use array_combine and array_reverse
$swapped = array_combine(array_keys($arr), array_reverse(array_values($arr)));
No. Use a temporary value:
$temp = $array['friend_id'];
$array['friend_id'] = $array['user_id'];
$array['user_id'] = $temp;
A bit longish, but I think it satisfies you requirements for 2 element arrays, just as you used in your example:
// your input array = $yourarray;
$keyarray = array_keys($yourarray);
$valuearray = array_values($yourarray);
/// empty input array just to make sure
$yourarray = array();
$yourarray[$keyarray[0]] = $valuearray[1];
$yourarray[$keyarray[1]] = $valuearray[0];
Basically Orangepill's answer done manually...
How about using array_flip?
array array_flip ( array $trans )
$myar = array('apples', 'oranges', 'pineaples'); print_r($myar);
print_r(array_flip($myar));
Array
(
[0] => apples
[1] => oranges
[2] => pineaples
)
Array
(
[apples] => 0
[oranges] => 1
[pineaples] => 2
)
$tmp = $array['user_id'];
$array['user_id'] = $array['friend_id'];
$array['friend_id'] = $tmp;
i couldn't find anything so i just wanted to take a url and then split it and turn it into key value pairs.
$url = 'http://domain.com/var/1/var2/2';
i am currently using a array_chunk on the path after using a parse_url
$u = parse_url($url);
$decoded = array_chunk($u['path'],2);
but it returns
array (
[0] => array (
[0] => var
[1] => 1
),
[1] => array (
[0] => var2
[1] => 2
)
)
what i would like is
array (
[var] => 1,
[var2] => 2
)
is there a Zend Framework method that is available to decode this into an array?
I'd use request object.
$url = 'http://domain.com/var/1/var2/2';
$request = new Zend_Controller_Request_Http($url);
$params = $request->getParams();
// or
$param = $request->getParam('var', $defaultValueNull);
This has the advantage, that you don't have to use isset to check which keys were set.
$u = parse_url($url);
$decoded = array_chunk($u['path'],2);
$new = array();
for ($decoded as $pair) {
$new[$pair[0]] = $pair[1];
}
print_r($new);
outputs
array (
[var] => 1,
[var2] => 2
)
If you're in the Controller it's simply
$data = $this->_getAllParams();
unset($data['module'], $data['controller'], $data['action']);
$data will now be
array (
[var] => 1,
[var] => 2
)
Hopefully you're not POSTing variables as well or this will also include the POST'd variables.
I have an array that is structured like this:
[33] => Array
(
[time] => 1285571561
[user] => test0
)
[34] => Array
(
[time] => 1285571659
[user] => test1
)
[35] => Array
(
[time] => 1285571682
[user] => test2
)
How can I get the last value in the array, but maintaining the index [35]?
The outcome that I am looking for is this:
[35] => Array
(
[time] => 1285571682
[user] => test2
)
try to use
end($array);
$last = array_slice($array, -1, 1, true);
See http://php.net/array_slice for details on what the arguments mean.
P.S. Unlike the other answers, this one actually does what you want. :-)
You can use end to advance the internal pointer to the end or array_slice to get an array only containing the last element:
$last = end($arr);
$last = current(array_slice($arr, -1));
If you have an array
$last_element = array_pop(array);
Example 1:
$arr = array("a"=>"a", "5"=>"b", "c", "key"=>"d", "lastkey"=>"e");
print_r(end($arr));
Output = e
Example 2:
ARRAY without key(s)
$arr = array("a", "b", "c", "d", "e");
print_r(array_slice($arr, -1, 1, true));
// output is = array( [4] => e )
Example 3:
ARRAY with key(s)
$arr = array("a"=>"a", "5"=>"b", "c", "key"=>"d", "lastkey"=>"e");
print_r(array_slice($arr, -1, 1, true));
// output is = array ( [lastkey] => e )
Example 4:
If your array keys like : [0] [1] [2] [3] [4] ... etc. You can use this:
$arr = array("a","b","c","d","e");
$lastindex = count($arr)-1;
print_r($lastindex);
Output = 4
Example 5:
But if you are not sure!
$arr = array("a"=>"a", "5"=>"b", "c", "key"=>"d", "lastkey"=>"e");
$ar_k = array_keys($arr);
$lastindex = $ar_k [ count($ar_k) - 1 ];
print_r($lastindex);
Output = lastkey
Resources:
https://php.net/array_slice
https://www.php.net/manual/en/function.array-keys.php
https://www.php.net/manual/en/function.count.php
https://www.php.net/manual/en/function.end.php
Like said Gumbo,
<?php
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
?>
Another solution cold be:
$value = $arr[count($arr) - 1];
The above will count the amount of array values, substract 1 and then return the value.
Note: This can only be used if your array keys are numeric.
As the key is needed, the accepted solution doesn't work.
This:
end($array);
return array(key($array) => array_pop($array));
will return exactly as the example in the question.
"SPL-way":
$splArray = SplFixedArray::fromArray($array);
$last_item_with_preserved_index[$splArray->getSize()-1] = $splArray->offsetGet($splArray->getSize()-1);
Read more about SplFixedArray and why it's in some cases ( especially with big-index sizes array-data) more preferable than basic array here => The SplFixedArray class.