1

I want to get all the array data where keys has the characters 'ch' from the start. How do I get it?

Array ( [editpostid] => 0 [editpostcat] => 1 [ch114] => on [ch115] => on )

The keys of the data may vary as the numbers come from the record id's from the database.

how do I place all the data with 'ch' in the start of keys on to a separate array?

2 Answers 2

1

Do like this

<?php
$arr = array('ch'=>10,'abch'=>20,'ch23'=>45);
$newarr=array();
foreach($arr as $k=>$v)
{
if(substr(strtolower($k),0,2)=='ch')
{
array_push($newarr,$v); // Make use of this if you just need the values
//$newarr[$k]=$v; // Uncomment this and comment above statement, if you need the keys too 
}
}
print_r($newarr);

OUTPUT:

Array
(
    [0] => 10
    [1] => 45
)
Sign up to request clarification or add additional context in comments.

1 Comment

that has the characters 'ch' from the start.: This will get those which have ch anywhere. Unless that's what they want, because they list contradictory requirements in the question
1
$charray=array();
foreach($yourarray as $key=>$value){
        if(preg_match("/^ch/",$key)){
            $charray[$key]=>$value;
        }
    }
//$charray is the new arrayas you asked for
echo implode(',',$charray);

refer official documentation for preg_match for more information

2 Comments

@sectus.. Thanks for letting me know.. i have modified it :)
No need for regex here, avoid wherever possible. bradt.ca/blog/stop-avoiding-regular-expressions-damn-it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.