Which is the best way to insert a new number in an already ascendant ordered array?
$new_number = 6;
$old_array = array(1,3,4,5,7,8,10);
// $new_array must be 1,3,4,5,6,7,8,10
Why not just add it and sort it again ?
$new_number = 6;
$old_array = array(1,3,4,5,7,8,10);
array_push($old_array,$new_number);
sort($old_array);
Simple:
$old_array = array(1,3,4,5,7,8,10);
$old_array[] = 6;
sort($old_array);
/* Notes:
sort() will actually change the array which you pass to it
don't do: $old_array = sort($old_array);
*/
Related
I have some arrays extracted from a XML-file. These are in
$array0 = (.......)
$array1 = (.......)
...
$arrayN = (.......)
Now I need a single array with all arrays in it separated by "," as
$masterArray = array($array0,
$array1,
...
$arrayN)
I tried
for ( $i = 0; $i < N; $i++) {
$masterArray = $masterArray + $array[$i];
}
with no result. I tried array_merge but this will give one
$masterArray(......................all items of all $arrays.....)
How can I do it right?
for ( $i = 0; $i < N; $i++) {
$temp = "array".$i;
$masterArray[$i] = ${$temp};
}
Given your exact definition of what you got and what you want the routine should be:
for ( $i = 0; $i < N; $i++) $masterArray[] = ${'array'.$i};
Not much to explain here. You make a new entry in an array with $variable[] = <entry>; and you access your numbered array with a variable variable, see:
http://php.net/manual/en/language.variables.variable.php
I guess you wont to create a multi dimension array:
$masterArray = array();
$masterArray[] = $array0;
$masterArray[] = $array1;
...
$masterArray[] = $arrayN;
this will in all arrays as element of the MasterArray:
$masterArray[0=>(....),1=>(....), ...];
Then access it like this:
$arr1_key1 = $masterArray[1]['key1'] ; //$array1['key1'];
You can add specific keys if you wont:
$masterArray['arr1'] = $array1;
$arr1_key1 = $masterArray['arr1']['key1'] ; //$array1['key1']
In general read some more to get better understanding on how to work with arrays ;)
I hope my question adequately describes what I'm after...
Here is the situation. I have the following arrays with values.
categories['t-shirts'] = 10
categories['shorts'] = 11
...
clothing[0] = 't-shirts'
clothing[1] = 'shorts'
...
I want to replace the values in the clothing array (t-shirts, shorts) with the number that matches it from the categories array.
Cheers
foreach($clothing as $key => $val){
if(isset($categories[$val])){
$clothing[$key] = $categories[$val];
}
}
Codepad Example
You can use simple php
categories[clothing[0]] = "some value"
From your question, it looks like
$newArray=array_keys($originalArray);
should do the trick.
$count = count($clothing);
for($i=0; $i<$count; $i++)
$clothing[$i] = (array_key_exists($clothing[$i], $categories))
? $categories[$clothing[$i]] : 0;
for setting the $clothings without any count to 0
$categories = array();
$categories['t-shirts'] = 10;
$categories['shorts'] = 11;
$clothing = array();
$clothing[0] = 't-shirts';
$clothing[1] = 'shorts';
array_walk($clothing,
function(&$value) use($categories) {
if (isset($categories[$value]))
$value = $categories[$value];
}
);
var_dump($clothing);
Ok, I have an array like so:
$myArray[32]['value'] = 'value1';
$myArray[32]['type'] = 'type1';
$myArray[33]['value'] = 'value2';
$myArray[33]['type'] = 'type2';
$myArray[35]['value'] = 'value3';
$myArray[42]['value'] = 'value4';
$myArray[42]['type'] = 'type4';
Ok, looking for a quick way to change all numbers in the first key 32, 33, 35, and 42 into 0, 1, 2, and 3 instead. But I need to preserve the 2nd key and all of the values. The array is already ordered correctly, since I ordered it using a ksort, but now I need to reset the array from 0 - count($myArray) - 1 and keep the 2nd key intact and its value as well.
Can someone please help me?
$myArray = array_values($myArray);
There might be simpler solutions but here is one working solution:
$myArray = array();
$myArray[32]['value'] = 'value1';
$myArray[32]['type'] = 'type1';
$myArray[33]['value'] = 'value2';
$myArray[33]['type'] = 'type2';
$myArray[35]['value'] = 'value3';
$myArray[42]['value'] = 'value4';
$myArray[42]['type'] = 'type4';
$map = array_flip(array_keys($myArray)); // map old keys to new keys.
$newarray = array();
foreach($myArray as $key => $value) {
$newarray[$map[$key]] = $value; // use new key and old value.
}
You don't need it. Why not to just leave this array alone? Unnecessary moves would lead your code to a mess.
I have a variable holding values separated by a comma (Implode), and I'm trying to get the total count of the values in that variable. However. count() is just returning 1.
I've tried converting the comma-separated values to a properly formatted array which still spits out1.
So here is the quick snippet where the sarray session is equal to value1,value2,value3:
$schools = $_SESSION['sarray'];
$result = count($schools);
You need to explode $schools into an actual array:
$schools = $_SESSION['sarray'];
$schools_array = explode(",", $schools);
$result = count($schools_array);
if you just need the count, and are 100% sure it's a clean comma separated list, you could also use substr_count() which may be marginally faster and, more importantly, easier on memory with very large sets of data:
$result = substr_count( $_SESSION['sarray'], ",") +1;
// add 1 if list is always a,b,c;
Should be
$result = count(explode(',',$schools));
Actually, its simpler than that:
$count = substr_count($schools, ',') + 1;
If there is sarray key set in session array, the count will return 1 for an empty string as well.
$session = array('sarray' => '');
$count = count(explode(',', $session['sarray']));
echo $count;
// => 1
So, if you want to count the number of items in the array, you will have to add an additional check for empty.
$session = array('sarray' => '');
$count = !empty($session['sarray']) ? count(explode(',', $session['sarray'])) : 0;
echo $count;
// => 0
Now, let's check if this works with items inside sarray.
$session = array('sarray' => 'foo, bar');
$count = !empty($session['sarray']) ? count(explode(',', $session['sarray'])) : 0;
echo $count;
// => 2
Hope this helps.
$schools = $_SESSION['sarray'];
$array = explode(',', $schools); array_walk($array, 'trim');
$count = count($array);
The array_walk($array, 'trim') will remove any trailing space in elements value. :)
$arr[] = $new_item;
Is it possible to get the newly pushed item programmatically?
Note that it's not necessary count($arr)-1:
$arr[1]=2;
$arr[] = $new_item;
In the above case,it's 2
end() do the job , to return the value ,
if its help to you ,
you can use key() after to petch the key.
after i wrote the answer , i see function in this link :
http://www.php.net/manual/en/function.end.php
function endKey($array){
end($array);
return key($array);
}
max(array_keys($array)) should do the trick
The safest way of doing it is:
$newKey = array_push($array, $newItem) - 1;
You can try:
max(array_keys($array,$new_item))
array_keys($array,$new_item) will return all the keys associated with value $new_item, as an array.
Of all these keys we are interested in the one that got added last and will have the max value.
You could use a variable to keep track of the number of items in an array:
$i = 0;
$foo = array();
$foo[++$i] = "hello";
$foo[++$i] = "world";
echo "Elements in array: $i" . PHP_EOL;
echo var_dump($foo);
if it's newly created, you should probably keep a reference to the element. :)
You could use array_reverse, like this:
$arr[] = $new_item;
...
$temp = array_reverse($arr);
$new_item = $temp[0];
Or you could do this:
$arr[] = $new_item;
...
$new_item = array_pop($arr);
$arr[] = $new_item;
If you are using the array as a stack, which it seems like you are, you should avoid mixing in associative keys. This includes setting $arr[$n] where $n > count($arr). Stick to using array_* functions for manipulation, and if you must use indexes only do so if 0 < $n < count($arr). That way, indexes should stay ordered and sequential, and then you can rely on $arr[count($arr)-1] to be correct (if it's not, you have a logic error).