I have an array looks like
Array
(
[0] => 1213059
[1] => 1213063
[2] =>
[3] =>
[4] => 1213072
)
I would like to make it as following:
Array
(
[0] => 1213059
[1] => 1213063
[2] => 1213072
)
Is there anyone can help me?
Many thanks
Use array_filter
Check demo here:
array_values(array_filter($your_array)); to keep your keys numerically .
array_filter will remove all elements that evaluate to false:
$array = array_filter($array);
I don't think answers above give correct fields order, as it was asked. If you only want to remove some fields from array and leave keys order untouched you could do it with
array_filter($arr) or with unset($arr[$i])
But if you want to get new order of keys, so there is no "holes", in above example to set key 4 to key 2 as keys 2 and 3 are unset, you have to use
ksort($arr)
Here is a complete example:
$arr=array(1,1,3,2,0);
print_r($arr);
echo '<br>';
unset($arr[2]);
ksort($arr);
print_r($arr);
$arr=array_values($arr);#EDITED
ksort($arr) knows not to sort array as it should, so just in case add $arr=array_values($arr); on the end #EDITED
PHP reference of ksort() is on link.
You may use this workaround.
Define this function somewhere:
function removeArrElement($inArr, $elementNr) {
for ($i = $elementNr; $i < count($inArr) - 1; $i++) {
$inArr[$i] = $inArr[$i + 1];
}
unset($inArr[count($inArr) - 1]);
return $inArr;
}
And then, when you want to remove the specific element from $yourArray, do this:
$yourArray = removeArrElement($yourArray, $nthElement);
I feel it's not the most efficient way to do this, but it works fine.
Related
I have this type of array,
Array
(
[0] => Array
(
[id] => 0
[fams] => 5
)
[1] => Array --> I want to remove this value using its index, which is "1"
(
[id] => 2
[fams] => 5
)
)
I want to remove that array [1] entirely, using its index, so the condition is - where the ID is match, for example - [id] => 2
Is that possible, to remove a particular value with that specific condition?
and without looping (or any similar method that need to loop the array)
thanks in advance!
FYI - I did try to search around, but, to be honest, I'm not sure what "keyword" do I need to use.
I did try before, but I found, array_search, array_keys - and it seems those 2 are not.
I'm okay, if we need several steps, as long as it did not use "loop" method.
---update
I forgot to mention, that I'm using old PHP 5.3.
array_filter should work fine with PHP 5.3.
The downside of this approach is that array_filter will (internally) iterate over all your array's entries, even after finding the right one (it's not a "short-circuit" approach). But at least, it's quick to write and shouldn't make much of a difference unless you're dealing with very big arrays.
Note: you should definitely upgrade your PHP version anyway!
$array = array (
0 =>
array (
'id' => 0,
'fams' => 5
),
1 =>
array (
'id' => 2,
'fams' => 5
)
);
$indexToRemove = 2;
$resultArray = array_filter($array, function ($entry) use ($indexToRemove) {
return $entry['id'] !== $indexToRemove;
});
Demo: https://3v4l.org/6DXjl
You can use array_search to find the key of a sub-array that has a matching id value (extracted using array_column), and if found, unset that element:
if (($k = array_search(2, array_column($array, 'id'))) !== false) {
unset($array[$k]);
}
print_r($array);
Output:
Array
(
[0] => Array
(
[id] => 0
[fams] => 5
)
)
Demo on 3v4l.org
It should be noted that although there is no explicit loop in this code, array_search and array_column both loop through the array internally.
You can use array_column to make id as index of the sub-array then use unset
$a = array_column($a, null, 'id');//new array id as index
$index = 2;// id to remove
if($a[$index]) unset($a[$index]);
print_r($a);
Working example :- https://3v4l.org/ofMr7
I'm getting started with PHP and I have some troubles finding a way to output values from multiples arrays sent from an external site.
I did a foreach and the code that is printed looks like this :
Array
(
[id] => 1
[title] => Title 1
)
Array
(
[id] => 2
[title] => Title 2
)
Array
(
[id] => 3
[title] => Title 3
)
Any idea how I could get every id (1,2,3) in an echo?
Let me know if you need more informations!
Thanks a lot!
If you just want to echo all the id's in all the arrays, a simple solution would be:
foreach ([$array1, $array2, $array3] as $arr) {
echo $arr['id'];
}
A better solution would probably to create one main array first:
$mainArray = [];
and every time you get a new array, you just push them to the main array:
$mainArray[] = $array1;
$mainArray[] = $array2;
// ... and so on
Then you'll have a multi dimensional array and can loop them with:
foreach ($mainArray as $arr) {
echo $arr['id'];
}
Which solution that works best depends on how you get the arrays and how many they are.
Note: Using array_merge() as others have suggested will not work in this case, since all the arrays have the same keys. From the documentation on array_merge(): "If the input arrays have the same string keys, then the later value for that key will overwrite the previous one."
As you can do:
$array = array_merge_recursive($arr1, $arr2, $arr3);
var_dump($newArray['id']);
echo implode(",", $newArray['id']);
A demo code is here
I am trying to separate an array into two separate arrays. For example, if I have an array like this
Array([0]=>Hello[1]=>I'm[2]=>Cam)
I want to split it into two arrays and add another string
Array1([0]=>Hello[1]=>There,)
Array2([0]=>I'm[1]=>Cam)
Then finally add the two together
Array([0]=>Hello[1]=>There,[2]=>I'm[3]=>Cam)
What would be the simplest way to do this?
I know I can use array merge to put the two together but I don't know how to separate them at a certain point.
I'm also doing this on a large file that will be constantly getting bigger, so I cant use array_chunk()
Looking at your end result goal, I think a shorter method to get your desired response is to use array_splice which lets you insert into a middle of an array....
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$arrayVarExtra = array('There');
array_splice($arrayVarOriginal, 1, 0, $arrayVarExtra);
This should send you back Array([0]=>Hello[1]=>There,[2]=>Im[3]=>Cam) like you wanted!
The above avoids having to split up the array.
HOWEVER
If you did want to do it the hard way, here is how you would...
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$array1stPart = array(arrayVarOriginal[0], 'There');
$array2ndPart = array_shift($array1stPart);
$finalArray = array_merge($array1stPart, $array2ndPart);
How? array_shift removes the first item from any array, so that how we get $array2ndPart.... and $array1stPart is even easier as we can just manually build up a brand new array and take the first item from $arrayVarOriginal which is at position 0 and add 'There' in as our own new position 1.
Hope that helps :)
array_shift, array_splice, and array_merge are what you need to look into.
Based from your question, here step-by-step to get what you want for your final output.
1) Split Array
$arr = array('Hello', 'I\'m', 'Cam');
$slice = count($arr) - 1;
$arr1 = array_slice($arr, 0, -$slice);
$arr2 = array_slice($arr,1);
so, you get two new array here $arr1 and $arr2
2) Add new string
$arr1[] = "There";
3) Finally, combine the array
$arr = array_merge($arr1, $arr2)
Here sample output when you print_r the $arr
Array
(
[0] => Hello
[1] => There
[2] => I'm
[3] => Cam
)
array_slice second parameter is position where you want split. So you can do this dynamically by count the array length.
$string = array("Hello","I'm","Cam");
$firstArray = array_slice($string ,0,1);
array_push($firstArray,"There,");
$secondArray = array_slice($string ,1,2);
echo "<pre>";
print_r($firstArray);
echo "==========="."<pre>";
print_r($secondArray);
echo "<pre>";
print_r(array_merge($firstArray,$secondArray));
//out put
Array
(
[0] => Hello
[1] => There,
)
===========
Array
(
[0] => I'm
[1] => Cam
)
Array
(
[0] => Hello
[1] => There,
[2] => I'm
[3] => Cam
)
Hope it will be worked for your requirement. If not or you need more specify regarding this you can clarify your need.
By default mysql_fetch_array returns numeric and associative array togeather. This function is useful for reading, while you can get values
either by statement :
echo arr[1]; //circle
or
echo arr["shape"]; //circle
I am new to PHP and I run into the troubles when I wanted to change the values of that fetched array:
arr[1] = square;
I supposed that arr["shape"] will be 'square' too, but I was wrong. arr["shape"] still remains 'circle'.
Obviously you have to change both values to 'circle'.
Moreover: I wrote a funcion which should return changed shape array, (which is 2D array). I got different outcomes, if I used the first or
the second line of code.
function ChangeShape($arr)
{
for ($i=0; $i<$count($arr); $i++)
{
1. $arr[$i]["shape"] = 'square'; // fail to return changed $arr - it is (probably) reference to number counterpart
2. $arr[$i][2] = 'square'; // this WILL return changed $arr
}
}
return $arr;
}
My questions:
1. is there any technique in PHP by which I can change both values at once?
2. in my app I use assoc nicknames to access array values. But when it is not possible to change numeric alias at the same time, what is
the easiest way to do it?
thank for reading this to the end... hope you answer.
Thanks a lot.
If you just want the data in a simple array once you grab it, you can always just simplify it by putting it in a few array:
$query = "SELECT * from myTable";
$result = mysql_query($query) or die(mysql_error());
$newArray = array();
$i=0;
while($row = mysql_fetch_array($result)){
array_push( $newArray, $row[$i]['name'] );
}
print_r($newArray);
$newArray[4] = "some other value than what came from the db";
print_r($newArray);
It doesn't seem super clear why your data is coming back as complicated as it seems to be, but this might help clear it up.
Do you really need to fetch numeric index? At least based on what you've posted it seems like you just want to call mysql_fetch_assoc to get an array with just the associative version.
The "aliases" in the array returned by mysql_fetch_array aren't really aliases... it just inserts it twice into the result array, once with the numeric index and once with the name of the column. The only way to change them both is to assign them both the desired value.
See this example and maybe it will make sense why its not working. Its not a reference or it would be working. If you had to have this functionality, you could build your array like this:
<?
$a='dog';
$b='cat';
$arr=array ('a' => &$a, 1 => &$a,'b' => &$b,'2' => &$b );
print_r($arr);
$a='horse';
print_r($arr);
$arr[1]='cow';
print_r($arr);
Results:
Array
(
[a] => dog
[1] => dog
[b] => cat
[2] => cat
)
Array
(
[a] => horse
[1] => horse
[b] => cat
[2] => cat
)
Array
(
[a] => cow
[1] => cow
[b] => cat
[2] => cat
)
I'm new to working with arrays so I need some help. With getting just one vaule from an array. I have an original array that looks like this:
$array1= Array(
[0] => 1_31
[1] => 1_65
[2] => 29_885...)
What I'm trying to do is seach for and return just the value after the underscore. I've figured out how to get that data into a second array and return the vaules as a new array.
foreach($array1 as $key => $value){
$id = explode('_',$value);
}
which gives me:
Array ( [0] => 1 [1] => 31 )
Array ( [0] => 1 [1] => 65 )
Array ( [0] => 29 [1] => 885 )
I can also get a list of the id's or part after the underscore by using $id[1] I'm just not sure if this is the best way and if it is how to do a search. I've tried using in_array() but that searches the whole array and I couldn't make it just search one key of the array.
Any help would be great.
If the part after underscore is unique, make it a key for new array:
$newArray = array();
foreach($array1 as $key => $value){
list($v,$k) = explode('_',$value);
$newArray[$k] = $v;
}
So you can check for key existence with isset($newArray[$mykey]), which will be more efficient.
You can use preg_grep() to grep an array:
$array1= array("1_31", "1_65", "29_885");
$num = 65;
print_r(preg_grep("/^\d+_$num$/", $array1));
Outputs:
Array
(
[1] => 1_65
)
See http://ideone.com/3Fgr8
I would say you're doing it just about as well as anyone else would.
EDIT
Alternate method:
$array1 = array_map(create_function('$a','$_ = explode("_",$a); return $_[1];'),$array1);
echo in_array(3,$array1) ? "yes" : "no"; // 3 being the example
I would have to agree. If you wish to see is a value exists in an array however just use the 'array_key_exists' function, if it returns true use the value for whatever.